如何在两个" h2"之间选择元素?除了一个使用jquery的元素?

时间:2016-10-11 19:38:46

标签: javascript jquery html selector nextuntil

所以我正在使用这样设计的网站:

<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>

我想使用jQuery在解释标题和transcript标题之间选择所有内容,但我在获取任何文本时都遇到了问题。我目前获得的jQuery如下:

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

但是现在,我根本不会选择任何文字。另外,我不确定如何只获取a和p文本而不是表格文本。非常感谢你们给我的任何帮助,谢谢!

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

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

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

alert(txt)
&#13;
<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>
&#13;
&#13;
&#13;

" || "中使用join()分隔符只是为了明白分隔符在哪里...相应调整

相关问题