DOM: Re-inserting an element without removing it first

S

Stanimir Stamenkov

I've wondered if it is right thing to do:

element.parentNode.insertBefore(element, beforeElement);

where 'beforeElement' is one of the 'element.parentNode.childNodes'?

First, I've used:

var parentElement = element.parentNode;
parentElement.removeChild(element);
parentElement.insertBefore(element, beforeElement);

but then I've noticed it works without the remove statement, too.
 
M

Martin Honnen

Stanimir said:
I've wondered if it is right thing to do:

element.parentNode.insertBefore(element, beforeElement);

where 'beforeElement' is one of the 'element.parentNode.childNodes'?

First, I've used:

var parentElement = element.parentNode;
parentElement.removeChild(element);
parentElement.insertBefore(element, beforeElement);

but then I've noticed it works without the remove statement, too.

Yes, all those DOM methods that add/insert an element remove the element
first if it is already attached to the tree:


http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247:
insertBefore
Inserts the node newChild before the existing child node refChild.
If refChild is null, insert newChild at the end of the list of children.
If newChild is a DocumentFragment object, all of its children are
inserted, in the same order, before refChild. If the newChild is already
in the tree, it is first removed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top