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!
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With