chaonextdoor
chaonextdoor

Reputation: 5139

The jQuery :eq(index) selector

I want to use the jQuery :eq(index) selector dynamically, which means I want to supply a variable as the index and choose the corresponding element dynamically. But it seems that it doesn't work. I think it's because the quotation marks. As this selector is used as, for example, $('ul li:eq(3)'), when I provide a variable as the index, maybe the index is viewed as a part of the string in the selector instead of a variable. Is it right? How can I fix this and choose the element dynamically?

Upvotes: 4

Views: 10575

Answers (2)

iambriansreed
iambriansreed

Reputation: 22241

var index = 5;

The following would work in your example.

$('ul li:eq(' + index + ')')

But for better performance in modern browsers, use:

$('ul li').eq(index)

Another reason .eq() is better than :eq() is you can pass '.eq(-1)' to get the last element.

Source: http://api.jquery.com/eq-selector/

Upvotes: 6

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

Your suspicions are correct, a variable name inside a string is treated as part of the string, not a variable name. You want to use string concatenation to let Javascript know your variable is a variable. It would look like this:

$('ul li:eq(' + myVar + ')')

Now, myVar is being recognized as a variable, not as part of the string.

Upvotes: 3

Related Questions