Reputation: 171351
Consider the following HTML:
<div>
<p>Hello</p>
World
</div>
Why $("div").append($("p"));
first removes the <p>
from its original place?
Note: I don't want to create a second copy of <p>
. I just want to understand why jQuery removes the <p>
before appending it.
Upvotes: 3
Views: 399
Reputation: 102763
You're selecting a p-tag that is already in the DOM, then appending it somewhere else in the DOM. What would you expect to happen? Really the only options are 1) what you see, 2) duplicate the selected tag before appending it, or 3) throw an error because it's already in the DOM.
Upvotes: 0
Reputation: 707436
A DOM node can only be in one place at a time. So, if you call append to put an existing DOM node that is already inserted into the DOM, before it can be put somewhere new, it has to be removed from the place it's at.
The only other alternative would be to return an error and refuse to append a node that is already in the document. But, the designers decided that if you're calling append(), you must want it to be there so if it's currently somewhere else, then remove it from there first and then put it where you specified for it to be appended.
Note that jQuery's append()
models itself after the DOM method appendChild()
which has this documentation note on MDN:
If child is a reference to an existing node in the document, appendChild moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).
This also means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.
Upvotes: 2
Reputation: 129001
jQuery is just an abstraction of the DOM, and that's what the DOM appendChild
method does.
Adds the node
newChild
to the end of the list of children of this node. If thenewChild
is already in the tree, it is first removed.
In a way, it makes sense; a node has a parent, children, and some other things. If a node could be in multiple different places, it would have to have multiple parents and such. That would add a lot of unneeded complexity to the API.
Upvotes: 9
Reputation: 238747
Because you are selecting all paragraph tags and telling them to append to the div. you are not creating any new paragraph tags.
Upvotes: 0