2

I'm not sure how I would phrase this question, so I couldn't find anything online about it, but what reason would one have to 'select' an element twice with jquery? An app I'm trying to understand has multiple examples of this contained within it.

var t = $($("#slider li")[currentIndex]); IPS.SetTheme($($("#slider li")[currentIndex])); $($("#location li")[currentIndex]).addClass("selected"); 

Is it similar to why this is occasionally written as $(this) for scope reasons?

3 Answers 3

6

$(selector)[index] returns the naked DOM element, so you need to wrap it with $() to get a jQuery object.

Sign up to request clarification or add additional context in comments.

3 Comments

What's the difference between a naked DOM element and a jQuery object in this context?
So the difference is that naked DOM elements can't be altered with jQuery methods?
Alright, thank you. I feel like this was never mentioned to me while reading about jQuery, but I haven't exactly read everything.
2

I'm a little confused. But let me try to help you.

Well, about this:

var t = $($("#slider li")[currentIndex]); 

The var t is a jQuery object. So you can do:

t.hide(); // to hide the element t.show(); // to show the element t.css("color", "red"); // to make the text color red 

We are talking here about index. You can lear more on: http://api.jquery.com/index/

For example, we have this HTML code:

<ul id="slider"> <li>foo</li> <li>bar</li> <li>baz</li> </ul> 

So if we do:

var currentIndex = 0; // Setting the index 0 -> 0 is the first var t = $($("#slider li")[currentIndex]); // taking first li t.remove(); // removindo first li 

It will result into:

<ul id="slider"> <li>bar</li> <li>baz</li> </ul> 

What about the index?

<ul id="slider"> <li>foo</li> index 0 <li>bar</li> index 1 <li>baz</li> index 2 </ul> 

Comments

1

You don't need to rewrap your object twice.

You can limit the set of decorations to a single one by using the :eq() jquery selector:

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

$("#myId:eq(" + myIndex + ")") 

This is the way it is supposed to be if you just want to select an object by index. More performant (one less decoration) and best practice.

1 Comment

I believe he knows this. He's looking for a way to avoid the double decoration. The eq selector avoids this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.