edt edt - 1 month ago 18
jQuery Question

How to select all content between two tags in jQuery

I have a document with headings and unordered lists.

How can I use JQuery to select a given heading (by its unique class name) AND all content between that heading and the next heading?

Update:



Your suggestions are great, but aren't what I'm looking for. In the below code, for example, I would like to access only the "h1" with id of "heading2" and everything up to, but not including the "h1" with id of "heading3".

The jQuery examples provided above will access everyting after the first "h" tag that is not an "h" tag.

... or, correct me if I'm wrong :)

<h1 id="heading1">...</h1>
<ul>...</ul>
<p>...</p>
<ul>...</ul>
<p>...</p>
<h1 id="heading2" >...</h1>
<ul>...</ul>
<p>...</p>
<ul>...</ul>
<p>...</p>
<h1 id="heading3" >...</h1>
<ul>...</ul>
<p>...</p>
<ul>...</ul>
<p>...</p>

Answer

Two methods in particular would be very useful solving this problem: .nextUntil, and .andSelf. The first will grab all of the siblings following your selector, and the latter will lump in whatever is matched by your selector as well, giving you one jQuery object that includes them all:

$("#heading2")
    .nextUntil("#heading3").andSelf()
        .css("background", "red");

This results in the following:

enter image description here