Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap DOM child nodes in JavaScript?

What is the easiest way to swap the order of child nodes?

For example I want childNode[3] to be childNode[4] and vice-versa.

like image 565
Myforwik Avatar asked Mar 16 '12 05:03

Myforwik


People also ask

What is child node Dom?

In the HTML DOM (Document Object Model), an HTML document is a collection of nodes with (or without) child nodes. Nodes are element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes. Elements are only element nodes.

What is the difference between childNodes and children in Javascript?

The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes.

What is DOM node in Javascript?

The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain Node object.


2 Answers

There is no need for cloning. You can just move one node before the other. The .insertBefore() method will take it from its current location and insert it somewhere else (thus moving it):

childNode[4].parentNode.insertBefore(childNode[4], childNode[3]); 

You get the parent of the node. You then call the insertBefore method on the parent and you pass it the childNode[4] node and tell it you want it inserted before childNode[3]. That will give you the result of swapping their order so 4 will be before 3 when it's done.

Reference documentation on insertBefore.

Any node that is inserted into the DOM that is already in the DOM is first removed automatically and then inserted back so there is no need to manually remove it first.

like image 141
jfriend00 Avatar answered Sep 23 '22 01:09

jfriend00


Use .before or .after!

This is vanilla JS!

childNode[3].before(childNode[4]); 

or

childNode[4].after(childNode[3]); 

For more durability swapping, try:

function swap(node1, node2) {     const afterNode2 = node2.nextElementSibling;     const parent = node2.parentNode;     node1.replaceWith(node2);     parent.insertBefore(node1, afterNode2); } 

This should work, even if the parents don't match

Can I Use - 95% Jul '21

like image 37
Gibolt Avatar answered Sep 23 '22 01:09

Gibolt