Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selectors: select two elements, and all elements in between

I have a load of LIs inside an UL, and each one has a unique ID.

Given two IDs, what's the best way to select the two corresponding LIs, and all the LIs in between?

Thanks!

like image 405
aidan Avatar asked Apr 23 '10 12:04

aidan


People also ask

What is a multi element selector?

Description. This Multiple Elements selector selects the combined results of all the specified selectors E, F or G. You can specify any number of selectors to combine into a single result.

How will you select all the div elements on the page using jQuery?

The jQuery syntax is a little simpler, but not much more: $("div") is the jQuery equivalent to document. getElementsByTagName("div") . Here is the API documentation on jQuery's element selector: “Description: Selects all elements with the given tag name.


2 Answers

You can do it like this:

$('#id').nextUntil('#id2').andSelf().add('#id2') 

It's important to note that .nextUntil() does not include the element it's going until, it stops with the one before it. To add that element, you need to call .add(selector) on the end.

You also need a .andSelf() to include the first element

Update August 2017

jQuery method .andSelf() is now deprecated in jQuery 1.8+, use .addBack() instead to add the first selection back. Also,.prevUntil() can be used if last element (#id2) percedes the first element (#id1) in the selection. Compare.index() for both elements to determine their order in the document.

like image 138
Nick Craver Avatar answered Sep 18 '22 19:09

Nick Craver


http://api.jquery.com/nextUntil/

Given a selector expression that represents a set of DOM elements, the .nextUntil() method searches through the successors of these elements in the DOM tree, stopping when it reaches an element matched by the method's argument. The new jQuery object that is returned contains all following siblings up to but not including the one matched by the .nextUntil() argument.

If the selector is not matched or is not supplied, all following siblings will be selected; in these cases it selects the same elements as the .nextAll() method does when no filter selector is provided.

As of jQuery 1.6, A DOM node or jQuery object, instead of a selector, may be passed to the .nextUntil() method.

The method optionally accepts a selector expression for its second argument. If this argument is supplied, the elements will be filtered by testing whether they match it...

like image 29
jAndy Avatar answered Sep 19 '22 19:09

jAndy