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?
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>
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.
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.
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.
Following is the basic syntax for selecting HTML elements and then performing some action on the selected element(s): $(document). ready(function(){ $(selector).
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With