Keep your eye out for Mr Speaker and @twalve's frightfully good book, jQuery: Novice to Ninja - in stores NOW!

.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!

One Comment

  1. hank wrote:

    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

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*
Captcha! Please type 'lolz' *