Home & blog  /  Tag: siblings  /

How to: get the node index of an element

posted: 26 Jun '10 10:12 tags: siblings, index, Javascript, jQuery, how-to

Javascript has no in-built way of returning the node index of an element from amongst its siblings.

That is, if you have a

    of 5
  • s, and you click the second of them, how can you get JS to know it was the second?

    The trick is to count the node's previous siblings. If you count them then add one, you'll have the node index of your element. Here's a jQuery plugin for this:

    1jQuery.fn.nodeIndex = function() {

    2     return $(this).prevAll().length + 1;

    3};

    Here's how you'd use it:

    1$('ul#myUL li').click(function() {

    2     alert("You clicked

  • number "+$(this).nodeIndex());

    3});

This is a good opportunity to show just how much time and code frameworks like jQuery (motto: "write less, do more") can save. Here's the same thing in native Javascript:

1function nodeIndex(node) {

2     if (node && typeof node == 'object') {

3         var siblings = node.parentNode.childNodes;

4         var counter = 0;

5         for(var i=0; i

6             if (siblings[i].tagName != undefined)

7                 if (siblings[i] === node) break;

8             else

9                 counter++;

10         }

11         return counter;

12     }

13}

And to use this:

1var lis = document.getElementById('myUL').getElementsByTagName('li');

2for (var k=0; k

3     lis[k].onclick = function() {

4         alert(nodeIndex(this));

5     }

6}

The whole point of frameworks like jQuery is to automate industrial, utility tasks such as this.

post a comment
older posts >