Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining jQuery selectors :lt and :gt

I have a table with more than 9 rows.

If I do this : $('table tr:gt(3):lt(6)'), shall I receive 3 or 6 elements at the end, and why? Are all selectors applied to the same primary selection, or are they successively applied on different selections?

like image 1000
glmxndr Avatar asked Jul 16 '09 12:07

glmxndr


People also ask

Can you chain jQuery selectors?

However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s). Tip: This way, browsers do not have to find the same element(s) more than once. To chain an action, you simply append the action to the previous action.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

What is GT in jQuery?

jQuery :gt() Selector The :gt() selector selects elements with an index number higher than a specified number. The index numbers start at 0. This is mostly used together with another selector to select the last elements in a group (like in the example above).


2 Answers

They're applied sequentially, so first you will filter away the first four elements (:gt(3)), then you will filter away all elements after the sixth (:lt(6)) element of the already filtered set.

Imagine this HTML:

<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>

Then do the following jQuery:

$('br:gt(3):lt(6)').addClass('sel');

You will now have:

<br/><br/>
<br/><br/>
<br class="sel"/><br class="sel"/>
<br class="sel"/><br class="sel"/>
<br class="sel"/><br class="sel"/>
<br/><br/>
like image 70
Blixt Avatar answered Sep 21 '22 18:09

Blixt


I suggest you use the slice() method instead.

http://docs.jquery.com/Traversing/slice#startend

$('table tr').slice(2, 5).addClass("something");
like image 24
ScottE Avatar answered Sep 20 '22 18:09

ScottE