PDA

View Full Version : How can I "port" elements?



shachi
12-19-2006, 05:39 PM
Hello everyone,

Can anyone tell me how do I "port" elements from one node to other? What I mean is, if there is an element tree like this:



div_one >> div_1 -- div_2 -- div_3
div_two >> div_4 -- div_5

(>> means child and -- means sibling)

Now how do I change it to



div_one >> div_1 -- div_2 -- div_3 -- div_4 -- div_5
div_two


dynamically with javascript?

I hope I was able to clear my point.

Thank you for your time in this post.

mwinter
12-19-2006, 05:56 PM
div_one >> div_1 -- div_2 -- div_3
div_two >> div_4 -- div_5

(>> means child and -- means sibling)

Now how do I change it to



div_one >> div_1 -- div_2 -- div_3 -- div_4 -- div_5
div_two


Use the appendChild and insertBefore methods. If the element already exists in the document tree, it's removed from its current parent and reattached in the new location.

In this exact case, you could write something like:



while (div_two.firstChild)
div_one.appendChild(div_two.firstChild);

to remove all child nodes (not just elements), where div_one and div_two are references to elements.

Mike

shachi
12-19-2006, 06:22 PM
Thanks a lot mwinter. I think I'll use the appendChild method.



If the element already exists in the document tree, it's removed from its current parent and reattached in the new location.


Do you mean that if the element exists appendChild will automatically remove the element and append it to it's new parent?



while (div_two.firstChild)
div_one.appendChild(div_two.firstChild);


That's not "exactly" what I want. What I want is something like a sortable list in which a user can manipulate the elements.

mwinter
12-19-2006, 06:51 PM
If the element already exists in the document tree, it's removed from its current parent and reattached in the new location.

Do you mean that if the element exists appendChild will automatically remove the element and append it to it's new parent?

Yes.



That's not "exactly" what I want.

It's what you described, though you didn't discuss other nodes that might exist. I can't help it if the two aren't the same. :)

Mike

shachi
12-19-2006, 07:00 PM
It's what you described, though you didn't discuss other nodes that might exist. I can't help it if the two aren't the same.


I thought you already understood what I wanted. Sorry for the mistake. :(