1

so I'm working with a website that is designed like this:

<h2>
  <span id="Explanation"> Explanation </span>
</h2>
<table> ... don't select anything in this table </table>
<a href="https://www.google.com/">hey</a>
<p> What's up? </p>
<p> How's life? </p>
<h2>
  <span id="Transcript"> Transcript </span>
</h2>
<p> Don't select this </p>

I want to select everything in between the explanation header and the transcript header using jQuery, but I'm having trouble getting any text at all. My current jQuery to get this is as follows:

explanation = "";
explanation = $("h2 #Explanation").nextUntil("h2 #Transcript").text();

But right now, I don't select any text at all. Also, I'm not sure about how to get only the a and p text and not the table text. Any help you guys could give me would be much appreciated, thanks!

4

2 回答 2

2

您需要使用:has()选择器来选择h2具有特定子项并用于.not()从选择器集中删除特定元素。

$("h2:has(#Explanation)").nextUntil("h2:has(#Transcript)").not("table").text();

var explanation = $("h2:has(#Explanation)").nextUntil("h2:has(#Transcript)").not("table").text();
console.log(explanation);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>
  <span id="Explanation"> Explanation </span>
</h2>
<table><tr><td>table</td></tr></table>
<a href="https://www.google.com/">hey</a>
<p> What's up? </p>
<p> How's life? </p>
<h2>
  <span id="Transcript"> Transcript </span>
</h2>
<p> Don't select this </p>

于 2016-10-11T19:42:19.600 回答
1

以下不包括表格并映射到数组每个元素的文本,以便您可以分隔每个文本块。如果元素中没有空格,那么text()在整个集合上运行将不会留下任何分隔

var txt = $('#Explanation').parent().nextUntil('h2:has(#Transcript)').not('table').map(function() {
  return $(this).text()
}).get().join(' || ')

alert(txt)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2><span id="Explanation"> Explanation </span></h2>
<table>
  <tr>
    <td>... don't select anything in this table</td>
  </tr>
</table>
<a href="https://www.google.com/">hey</a>
<p>What's up?</p>
<p>How's life?</p>
<h2>
   <span id="Transcript"> Transcript </span>
 </h2>
<p>Don't select this</p>

使用" || "分隔符join()只是为了让分隔符在哪里变得明显......相应地调整

于 2016-10-11T19:51:34.757 回答