Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one determine the number of a list item in an ordered list using JavaScript?

Given an ordered HTML list, is there any way, given the list element, of determining it's number in JavaScript, besides looking at its location in the list?

For example, suppose I have a list

<ol start="4" type="i">
 <li>First</li>
 <li>Second</li>
</ol>

which is rendered as

iv. First
 v. Second

What is the best way using JavaScript (including jQuery) that, given on of the LI, to find out it's number?

The naive way is to look at the item's index, add the start value, and translate the type. But I am wondering if there's a better way.

like image 928
Rob Avatar asked Sep 17 '25 06:09

Rob


1 Answers

an example is to add an index property to the list item:

lets say your list has an id='ordered'

var ol = document.getElementById('ordered');

// select the list items
var lists = ol.getElementsByTagName('li');

// now loop through the items and set a custom property 'index'
var l = lists.length; // total items

for (var i=1;i<=l;i++){
  list[i].index = i;
}

now your list item will have an index property that you can access through javascript to determine its position.

<ol id='ordered'>
 <li index='1'>First</li>
 <li index='2'>Second</li>
</ol>
like image 137
Ibu Avatar answered Sep 19 '25 21:09

Ibu