Moving a DOM element

T

Tim Streater

Suppose (in JavaScript) I get a pointer to an element, this:

myPtr = document.getElementById ("wiggy");

and then I do this:

document.appendChild (myPtr);

does this move the element from wherever it was in the DOM, to the end
of the document? From some code I've seen I guess it must, because doing
this and then examining the DOM (with Safari web inspector) I see the
object at the end. Yet I've not seen this noted explicitly anywhere.

But I would have expected to have needed to do removeChild first.
 
S

Stanimir Stamenkov

Sun, 03 Jul 2011 13:58:11 +0100, /Tim Streater/:
myPtr = document.getElementById ("wiggy");

and then I do this:

document.appendChild (myPtr);

does this move the element from wherever it was in the DOM, to the
end of the document? From some code I've seen I guess it must,
because doing this and then examining the DOM (with Safari web
inspector) I see the object at the end. Yet I've not seen this noted
explicitly anywhere.

But I would have expected to have needed to do removeChild first.

No need of explicit 'removeChild' really
<http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-184E7107>:

| appendChild
| Adds the node newChild to the end of the list of children of
| this node. If the newChild is already in the tree, it is first
| removed.
|
| insertBefore
| ... If the newChild is already in the tree, it is first removed.
|
| replaceChild
| ... If the newChild is already in the tree, it is first removed.
 
J

Jukka K. Korpela

Suppose (in JavaScript) I get a pointer to an element, this:

myPtr = document.getElementById ("wiggy");

and then I do this:

document.appendChild (myPtr);

does this move the element from wherever it was in the DOM, to the end
of the document?

No, it does not, because it raises a hierarchy request error. But you
can use

document.body.appendChild (myPtr);
 

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

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top