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
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.
I am a Chinese student, want to learn JavaScript.