Reputation: 2811
I need to add a child div inside a parent div and then delete the child div in x sec.
There could be several children divs added to parent div.
What would the best way to identify and delete the child div?
$("#parent_div").prepend("<div>"+msg+"</div>");
Upvotes: 2
Views: 2724
Reputation: 333
Try this way:
$("<div/>", {
// PROPERTIES HERE
text: "Click me",
id: "example",
"class": "myDiv", // ('class' is still better in quotes)
css: {
color: "red",
fontSize: "3em",
cursor: "pointer"
},
on: {
mouseenter: function() {
console.log("PLEASE... "+ $(this).text());
},
click: function() {
console.log("Hy! My ID is: "+ this.id);
}
},
append: "<i>!!</i>",
appendTo: "body" // Finally, append to any selector
});
// And remove
setTimeout(() => {
$('.myDiv').remove();
}, 1000)
Upvotes: 0
Reputation: 1074118
By keeping a reference to it:
function doTheChildDivThing() {
var child = $("<div>" + msg + "</div>");
$("#parent").prepend(child);
setTimeout(function() {
child.remove();
}, 1000);
}
Re your comment below:
why delay() (instead of setTimeout) is not working in that case?
delay
works with the effects queue. remove
isn't an effects-related method. You could certainly use delay
with one of the effects methods, though, like slideUp
. Then you'd remove the child within the completion callback of the effects method, like this:
function doTheChildDivThing() {
var child = $("<div>" + msg + "</div>");
$("#parent").prepend(child);
child.delay(1000).slideUp(function() {
child.remove();
});
}
Upvotes: 7