Bluefire Bluefire - 2 months ago 13
jQuery Question

Find the first element with a certain class/tag name after another element

I have a web page that looks like this:

<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


How can I select the
<p class="paragraph">
tag after the heading with
id="b"
(with contents "stuff I need")?

I have thought about locating the index of
<h1 id="b">B</h1>
in
$("h1")
and then accessing that index in
$("p.paragraph")
, but that won't work in my specific case.

EDIT: a better example: https://jsfiddle.net/n7zstmw8/

Answer

The select is:

$('#b + .paragraph')

Next Adjacent Selector (“prev + next”): Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

The snippet:

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

If the next element is not adjacent you may use 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>

Comments