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.
You can use
previousElementSibling
to jump step-by-step to the beginning of the list and just count how many jumps you made: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 wherei
is declared do this: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:Live demo: http://jsfiddle.net/simevidas/U47wL/4/
jQuery solution:
Live demo: http://jsfiddle.net/simevidas/U47wL/5/
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:
The following javascript should return 1 (index starts from 0)
you can try getElementsByTagName in the parent of your li elements and traverse them, and increase the index,getElementsByTagNames results in same order as they appear in DOM tree. See this for example : http://jsfiddle.net/s3p7C/
// Not especially for lists, but this is a way to get the index of an element within its parent, from the element itself. It won't count any decendents of siblings, just siblings with the same tag.
This is one way to do it JSFiddle Demo:
By clicking on the
li
node it'llconsole.log
the index number