Reputation: 121
I have an application that's dynamically creates overlapping div boxes with the same content.
When I add the content to a box I append the content div to the class selector ".box" (I can't use id here because one id can only exist ones on the page). The problem is that the content gets applied to all the existing boxes every time a new box is created. I just want to add the content to the last created box.
What is the best way to do it?
// function that's applying the content into the new box:
var box = $('<div/>', {
'class': 'imgDiv',
}).appendTo('.box');
...
Upvotes: 0
Views: 175
Reputation: 3214
You can use the :last
modifier. Here is a working sample: http://jsfiddle.net/ayezutov/ZsBgY/2/
$("#append").click(function(e){
$("<div>appended</div>").appendTo(".box:last");
e.preventDefault();
});
Upvotes: 0
Reputation: 34717
You could try running a counter, and update each box's id with a that counter, ie: .attr('id','box-' + counter).
Upvotes: 0
Reputation: 23770
If you append to the .box
selector, the selector selects all the tags with the box tag. What you need is select only the specific box that you want to add the content to!
var box = $('<div/>', {
'class': 'imgDiv',
}).appendTo('#my_specific_box');
Or use a pseudo to select the last:
var box = $('<div/>', {
'class': 'imgDiv',
}).appendTo('.box:last');
Upvotes: 0
Reputation: 11327
If the last .box
created is the last on the page, you can do this:
var box = $('<div/>', {
'class': 'imgDiv',
}).appendTo( $('.box').last() );
Your var box =
is a little confusing though. If you're creating the new box
in the same section of code, you should just retain a reference to that new box, and append the content to that.
Upvotes: 1