Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Id's dynamically to DOM elements with javascript

Tags:

javascript

I just have a quick question about how to generate id's on-the-fly for HTML elements. So far I've tried a few things, I started with a "for" loop, I already know how many elements I have to generate Id's for, in this case I have an "ul" with 6 "li". My "for" loop is as follows:

var items = $("ul li").length;
for(var i = 0; i <= items; i++){
    $("ul li").attr("id", "number" + i);
}

"number" would be the new id concatenated with "i", so I get a different Id for each "li". As you can probably tell, this does not work, because I end up with the same Id for each "li":

in this case I get <li id="number6">... </li> for all the "li" elments in the "ul". I tried a "while" loop and ".each()" with jQuery but I get the exact same thing.

Any help would be appreciated.

like image 918
jnkrois Avatar asked Feb 19 '26 22:02

jnkrois


1 Answers

You can do this easier using a .each() (use this inside, not the selector again!), like this:

$("ul li").each(function(i) {
  $(this).attr("id", "number" + i);
});

The function in the .each() gets the index and element as a parameter, so you can just use that i to assign the ID starting at 0 like you have currently.

Or, alternatively, you can pass a similar function to .attr(), like this:

$("ul li").attr('id', function(i) {
  return "number" + i;
});
like image 179
Nick Craver Avatar answered Feb 21 '26 14:02

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!