Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate dynamic id using jQuery?

I want to add progressive id to a series of elements on an unordered HTML list. I used the jQuery .each() method to get each <li> of the List and append a <span> inside each <li>. Then I added the ID attribute with index of each() as number.

$('#menu li ul li').each(function(i, e){
    $(this).append('<span class="arr"></span>');
    $(".arr").attr("id", "id_" + i);
});

Fiddle Demo

But I get id_3 for all elements. Why? What did I do wrong?

Thanks for any help!

like image 802
Mustapha Aoussar Avatar asked Apr 07 '14 13:04

Mustapha Aoussar


1 Answers

It is because you are applying it to .arr globally, so overriding it every time.
You need to be more specific with adding it, by finding the .arr in you current li.

Change your code to be:

$('#menu li ul li').each(function(i, e){
    $(this).append('<span class="arr"></span>');
    $(this).find(".arr").attr("id", "id_" + i);
});
like image 141
putvande Avatar answered Sep 22 '22 19:09

putvande