Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Selecting" twice with jquery?

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?

like image 421
user2658433 Avatar asked Feb 13 '26 08:02

user2658433


2 Answers

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

like image 133
keune Avatar answered Feb 15 '26 21:02

keune


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>
like image 30
Felipe M Avatar answered Feb 15 '26 21:02

Felipe M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!