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?

royhowie
  • 11,075
  • 14
  • 50
  • 67

3 Answers3

6

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

keune
  • 5,779
  • 4
  • 34
  • 50
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>
Felipe M
  • 449
  • 1
  • 3
  • 14
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.