Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  186] [ 6]  / answers: 1 / hits: 32398  / 10 Years ago, mon, april 7, 2014, 12:00:00

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!


More From » jquery

 Answers
20

As has been pointed out, $(.arr) targets every element with the arr class, so on the fourth iteration you update all such elements to the id_3 id.



You can limit the selection with $(.arr, this) or $(this).find(.arr), but it would be easier to just turn the append around:



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


That is, create the element first, set its id, then use .appendTo() instead of .append().



Or rather than calling .attr() you can pass the desired attributes directly to the $() function when you create your span:



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

[#71576] Friday, April 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;