Hello

World Why does it $("div...">

Why does jQuery's "append ()" child first remove it?

Consider the following HTML:

<div>
    <p>Hello</p>
    World
</div>

      

Why does it $("div").append($("p"));

first delete <p>

from its original location?

Note: I don't want to create a second copy <p>

. I just want to understand why jQuery is removing <p>

before adding it.

+3


source to share


4 answers


jQuery is just an abstraction of the DOM and what the DOM method doesappendChild

.

Adds a node newChild

to the end of this node's list of children. If it is newChild

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.

+9


source


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 append()

models itself after the DOM method appendChild()

, 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.

+2


source


Because you select all the paragraph tags and tell them to add to the div. you are not creating any new paragraph tags.

0


source


You select a p tag that is already in the DOM and then add it somewhere else in the DOM. What would you expect? Actually the only parameters are 1) what you see, 2) duplicate the highlighted tag before adding it, or 3) throw an error because it's already in the DOM.

0


source







All Articles