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.
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.
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.
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.
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.
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With