Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Dustin Scott
Courses Plus Student 7,819 PointsHow to append a lot of divs with a unique id's
Hi,
How can I append a div using JQuery with a unique id? For example:
This is my JQuery code:
var counter = 1;
$('.button').click(function(){
$('.body_div').append('<div></div>');
var div ('.body_div > div');
$(div).addClass('selected');
if($(div).hasClass('selected')){
$(div).attr('id', 'id' + counter++);
}
});
If I click on the button the ID will be same for all the divs which is appended
1 Answer
Dino Paškvan
Courses Plus Student 44,108 PointsYou could do it like this:
var counter = 1;
$('.button').click(function(){
var $newDiv = $("<div></div>");
$newDiv.attr("id", "newDiv" + counter++);
$(".body_div").append($newDiv);
});
Here's a CodePen to illustrate.
Dustin Scott
Courses Plus Student 7,819 PointsYou really deserve more than "Best Answer". Thanks man.
Becky Castle
15,294 PointsBecky Castle
15,294 PointsHi Dustin, Can you explain this a little more? Do you have any html markup you could show for this example?