Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 339
edt Avatar asked Jan 26 '09 19:01

edt


People also ask

How to select jQuery elements?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What is multiple selector?

Multiple Selectors allow users to create back-ups for selectors designed to target elements on the page. They are especially useful for sites with rotating carousels, or elements that are dynamic.

Can you use CSS selectors in jQuery for selecting elements?

Projects In JavaScript & JQueryjQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element. name − The name of the property to access.

What is the syntax of jQuery to select and handle elements?

Following is the basic syntax for selecting HTML elements and then performing some action on the selected element(s): $(document). ready(function(){ $(selector).


1 Answers

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

like image 168
Sampson Avatar answered Sep 23 '22 20:09

Sampson