Why does jQuery's "append ()" child first remove it?
jQuery is just an abstraction of the DOM and what the DOM method does
Adds a node
to the end of this node's list of children. If it is
already in the tree, it is removed first.
In a way, it makes sense; a node has parent, children and some other stuff. If a node can be in several different locations, it must have multiple parents, etc. This would add a lot of unnecessary complexity to the API.
source to share
A DOM node can only be in one place at a time. So, if you call append to place an existing DOM node that is already inserted into the DOM, before it can be placed somewhere new, it needs to be removed from where it is.
The only alternative might be to return an error and refuse to add a node that is already in the document. But the designers decided that if you call append () you should want it to be there if it is currently somewhere else, then remove it first and then put it where you specified it to be was added.
Note that jQuery
models itself after the DOM method
, which has this documentation on MDN :
If the child is a reference to an existing node in the document, appendChild moves it from its current position to a new position (i.e. there is no requirement to remove a node from its parent node before adding it to another node).
This also means that a node cannot be at two points in the document at the same time. So if the node already has a parent, this is the first one removed and then added at the new position.
source to share