David
David

Reputation: 43

Jquery : how does index() works?

I try to understand how the jQuery Object Accessors index() works. But I don't understand anything! (see http://jsfiddle.net/St4D7/)

So I have a HTML list item:

<ul>
<li>test 1</li>
<li>test 2</li>
<li>test 3</li>
</ul>

And jQuery:

$('ul li').click(function(){
    console.log($(this).index());
});

I'd like to have the index position of items on click (like 1, 2 or 3), that's all. Please help.

PS : I don't want to use each() or eq()… just index().

Upvotes: 1

Views: 447

Answers (3)

Tomalak
Tomalak

Reputation: 338128

A look in the source helps:

index: function( elem ) {
  if ( !elem || typeof elem === "string" ) {
    return jQuery.inArray( this[0],
      // If it receives a string, the selector is used
      // If it receives nothing, the siblings are used
      elem ? jQuery( elem ) : this.parent().children() ); // <-- here
  }
  // Locate the position of the desired element
  return jQuery.inArray(
    // If it receives a jQuery object, the first element is used
    elem.jquery ? elem[0] : elem, this );
},

As you can see, index() calls inArray(), which returns a number.

When you give no argument, it branches into the if and effectively calls

return jQuery.inArray(this[0], this.parent().children());

In your case, this[0] is the <li> in question and this.parent().children() is all the children of the parent <ul>. inArray() returns the respective position.

This is not a very efficient way to do things and it can also produce different results when compared to the index parameter of the each() callback, because index() looks at all children:

<div>
  <p>A paragraph</p>
  <hr>
  <p>Another paragraph</p>
</div>

// this logs 0, 1 
$("div p").each(function (i) {
  console.log(i)
});

// this logs 0, 2 (!) 
$("div p").each(
  console.log( $(this).index() );
});

Upvotes: 0

Matt
Matt

Reputation: 75307

As described in the documentation, index returns the zero-indexed position of the first element depending on the parameters you provide, in the jQuery object you call it on.

However, you also seem to be slipping up on the context of this.

At the time you call $(this).index(), this points to the lil element that was clicked on. Therefore $(this) contains a jQuery object containing one element.

Instead, try something like this:

var obj = $('ul li').click(function(){
    console.log(obj.index(this));
});

Upvotes: 1

user342706
user342706

Reputation:

You need to wrap it in the document ready and chose jQuery as the javascript library on the left. Here is a working example: http://jsfiddle.net/keroger2k/St4D7/3/

Upvotes: 0

Related Questions