Adding auto increment value to li element
im a css/designer guy so please excuse my lameness in not knowing any .js
basically i want to know how to add an auto incremental id to a list item with javascript / jquery for something that i am trying to add some css to.
before
<li id=""><a href="">Item number 1</a></li>
<li id=""><a href="">Item number 2</a></li>
<li id=""><a href="">Item number 3</a></li>
after
<li i开发者_JAVA百科d="1"><a href="">Item number 1</a></li>
<li id="2"><a href="">Item number 2</a></li>
<li id="3"><a href="">Item number 3</a></li>
thanks in advance and especially just for reading this
tried all the responses, nothing has worked on a plain html page with nothing but the ul/li items.
thanks to all that tried, i have failed in a big way.....im not a coder
I'm going to give your li
tags an encompassing ul
with an id
in case there are other li
tags on the page that you don't want to order, but in jQuery this is pretty easy for:
<ul id="ordered">
<li><a href="">Item number 1</a></li>
<li><a href="">Item number 2</a></li>
<li><a href="">Item number 3</a></li>
</ul>
You would simply use the each
method:
$('#ordered li').each(function(i,el){
el.id = i+1;
});
I would recommend using something other than just a plain integer for an id though, so maybe something like 'ordered' + (i+1)
instead of just i+1
above.
Your tags say jQuery, so:
$("li").each(function(i){this.id = i})
So you can learn: you make a collection of HTML nodes with the $('foo')
syntax. You use CSS selectors, so li
will get -every- <li>
on the page.
.each
loops over those collected HTML elements, and does something to them. The 'something' is in the code function(i){this.id = i}
. jQuery passes which loop you're on to the function as i
, and the code inside the curly braces sets the id of that particular element to i
.
If you need id's for styling, that's a bad idea. What you should do is use css 3 pseudo class :nth-child(n) which is in your area of css.
I'm going to wrap your code in a div so it's easier to code for
<div id="increment">
<li><a href="">Item number 1</a></li>
<li><a href="">Item number 2</a></li>
<li><a href="">Item number 3</a></li>
</div>
And js would be:
function loadcode(){
var increments = document.getElementById("increment");
var li = increments.getElementsByTagName("li");
for (i=0;i<li.length;i++) li[i].setAttribute("id", i+1);
}
and in your HTML:
<body onload="loadcode()">
精彩评论