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

Given an ordered HTML list, is there any way given by the list item to determine its number in JavaScript, in addition to 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 displayed as

iv. First
 v. Second

What is the best way to use JavaScript (including jQuery) which, given the LI data, find out its number?

The naive way is to look at the index of the element, add the initial value and translate it. But I wonder if there is a better way.

+3
source share
4 answers

An example is to add an item property to a list item:

lets say that your list has 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;
}

, javascript, .

<ol id='ordered'>
 <li index='1'>First</li>
 <li index='2'>Second</li>
</ol>
+2

http://www.w3.org/TR/html-markup/li.html , value.

note: HTML5. HTML4.01 ol.start li.value . , , , HTML5.

+1

MDC <li> value, . HTML 4, HTML 5. , :

$("li").prop("value");  // jQuery 1.6 and higher
$("li").attr("value");  // jQuery 1.5 and lower

, , Firefox 3.6 ( -1). fiddle, .

+1

:)

I would say that it is better to enter data in each li element, you can put some HTML attributes inside li, but I'm afraid when you check the HTML, it will reject it.

So this is the code,

var lis = $("ol li").each(function(i, el)
{
    $(this).data("index", i);
});

and when you make your beautiful number, do the following:

$(this).data("index");

:)

+1
source

All Articles