Reputation: 1
I'm new to Javascript and jQuery so maybe this is a basic concept, but in the following code:
var toRemove = $("p").remove();
$("div").append(toRemove);
I remove the p element which I saw work in the UI and then I append it. Because it's removed, I would expect it to not append anything. But in the UI I see that it did. Why does it do that?
Demo: https://jsfiddle.net/4mthn93z/
Upvotes: 0
Views: 58
Reputation: 19772
Generally jQuery methods, when called on a collections of nodes, returns the same collection. This is what enables you to chain methods. E.g $("#id").html("Some contnet").hide();
Just because something has been removed from the DOM doesn't mean the javascript/jquery object has ceased to exist, it's just no longer part of the DOM. By assigning the result of the method to a variable, you have saved those objects for later use. This is actually a very handy feature.
Upvotes: 2
Reputation: 238
Because toRemove is a function. You can try..
var toRemove = $("p").remove();
$("div").append(toRemove());
Upvotes: 1