Mr Speaker

.index() becomes cool in jQuery 1.4

With jQuery 1.4 just around the corner, it's time to start looking at what's new. One nice change is the updated functionality of the index method. Previously, well, it was a pain in the bum to get the index of an element in a selection - and required a pretty convoluted syntax. Now it's super easy... $(this).index(). Let's have a look at a 'lil example:

Say we have an unordered list of items:

<ul id="tags">
	<li>jQuery</li>
	<li>Javascript</li>
	<li>reference</li>
	...
</ul>

The user can click on a list item to select it. When a click happens, we need to find out what the item's index is, relative to all its siblings....

$("#tags li").click(function(){
    alert( "Hi, I'm element " + $(this).index() ); 
});

That's all there is to it. Super useful!

2 Comments

  1. Glad to hear it, that one was always a bit of a pain. Relative to siblings is pretty much all you’d really want IMO.

    Sunday, December 6, 2009 at 6:56 am | Permalink
  2. I am a Chinese student, want to learn JavaScript.

    Thursday, April 15, 2010 at 3:49 pm | Permalink
Captcha! Please type 'radical' here: *
How did you find this thingo? *