在另一个元素之后找到具有某个类/标记名称的第一个元素

时间:2016-09-03 20:10:59

标签: javascript jquery html jquery-selectors

我有一个看起来像这样的网页:

<h1 id="a">A</h1>
contents
<p class="paragraph">stuff</p>
more contents

<h1 id="b">B</h1>
contents
<p class="paragraph">stuff I need</p>
more contents

<h1 id="c">C</h1>
contents
<p class="paragraph">stuff</p>
more contents

et cetera

如何在标题<p class="paragraph">后选择id="b"标记(内容为“我需要的内容”)?

我考虑过在<h1 id="b">B</h1>中查找$("h1")的索引,然后在$("p.paragraph")中访问该索引,但这在我的具体情况下无效。

编辑:一个更好的例子:https://jsfiddle.net/n7zstmw8/

1 个答案:

答案 0 :(得分:3)

选择是:

$('#b + .paragraph')
  

Next Adjacent Selector (“prev + next”):选择匹配“next”的所有下一个元素,这些元素后面紧跟一个兄弟“prev”。

摘录:

$(function () {
  console.log($('#b + .paragraph').text());
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<h1 id="a">A</h1>
contents
<p class="paragraph">stuff</p>
more contents

<h1 id="b">B</h1>
contents
<p class="paragraph">stuff I need</p>
more contents

<h1 id="c">C</h1>
contents
<p class="paragraph">stuff</p>
more contents

如果下一个元素不相邻,您可以使用nextAll:

$(function () {
  console.log($('#b').nextAll('.paragraph:first').text());
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<h1 id="a">A</h1>
<span class="inbetween">In between stuff</span>
<p class="paragraph">stuff</p>
<span class="inbetween">In between stuff</span>

<h1 id="b">B</h1>
<span class="inbetween">In between stuff</span>
<div class="moreinbetween">
    More stuff
</div>
<p class="paragraph">stuff I need</p>
<span class="inbetween">In between stuff</span>

<h1 id="c">C</h1>
<span class="inbetween">In between stuff</span>
<p class="paragraph">stuff</p>
<span class="inbetween">In between stuff</span>