Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a jQuery selector with multiple :eq's in single expression?

Tags:

I have a quick question. How do I write a jQuery selector expression with multiple :eq() selectors? I want to go down the DOM tree but every hope isn't uniform. Here is what I have that works:

$('div:eq(0)').find('div:eq(1)').find('div:eq(5)')

But is the following does not work:

$('div:eq(0) div:eq(1) div:eq(5)')

Is there a more elegant way to write it without all the "find"'s?

like image 210
thiesdiggity Avatar asked Dec 09 '11 17:12

thiesdiggity


2 Answers

I believe that you could do the following and it should return all dom elements that match:

 $('div:eq(0), div:eq(1), div:eq(5)')

You could then iterate over the results returned, hope this helps.

like image 93
mreyeros Avatar answered Oct 12 '22 08:10

mreyeros


Using an each loop - elegant and not repetitive:

$.each([0, 1, 5], (_, n) => {
    $('div').eq(n);
});

Last I checked, this technique performs best:

$('div').filter(':eq(0), :eq(1), :eq(5)');
like image 28
northamerican Avatar answered Oct 12 '22 07:10

northamerican