Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered List Index

Is there any way to get the number (index) of a li tag in an ordered list?

I'm trying to get the number that is shown on the side (the list numbering). I know that the traditional way is to use an id which stores the line number but this would mean that if a line is added in between, a lot of ids would have to be edited. Even though I have developed an algorithm for this, it is not so efficient.

I'm looking for a solution to use in Javascript.

like image 311
Diff.Thinkr Avatar asked Mar 22 '11 17:03

Diff.Thinkr


2 Answers

You can use previousElementSibling to jump step-by-step to the beginning of the list and just count how many jumps you made:

ol.onclick = function(e) {
    var li = e.target,
        i = 1;

    while ( li.previousElementSibling ) {
        li = li.previousElementSibling;
        i += 1;   
    }

    alert( 'Index = ' + i );
};

Note that Element Traversal is not implemented in IE8 or below (but it is in IE9).

Live demo: http://jsfiddle.net/simevidas/U47wL/


If you have the start attribute set on the OL element, then just modify the line where i is declared do this:

i = ol.start || 1;

Live demo: http://jsfiddle.net/simevidas/U47wL/2/


If you require a cross-browser solution, then you can use previousSibling and then check whether the sibling is an element node and only increment then:

ol.onclick = function(e) {
    var e = e || window.event,
        li = e.target || e.srcElement,
        i = ol.start || 1;

    while ( li.previousSibling ) {
        li = li.previousSibling;
        if ( li.nodeType === 1 ) { i += 1; }   
    }

    alert( 'Index = ' + i );
};

Live demo: http://jsfiddle.net/simevidas/U47wL/4/


jQuery solution:

$('ol').click(function(e) {
    var n = $(e.target).index() + this.start;

    alert( 'Index = ' + n );    
});

Live demo: http://jsfiddle.net/simevidas/U47wL/5/

like image 68
Šime Vidas Avatar answered Sep 21 '22 20:09

Šime Vidas


jQuery has an .index() function which returns the position of the element within it's parent. That should do what you are asking for, as long as you are happy using jQuery.

For example, given the following HTML:

<ul>
    <li></li>
    <li class="myli"></li>
    <li></li>
</ul>

The following javascript should return 1 (index starts from 0)

$('.myli').index();
like image 21
beeglebug Avatar answered Sep 21 '22 20:09

beeglebug