Insert item

Is there a way in Javascript to insert an element after the current node. I know that there is a method that inserts an element before the current XML node. But is there an Ins method. after current node?

+3
source share
2 answers

Just select the next brother of the current node and insert a new node before this node using insertBefore

currentNode.parentNode.insertBefore(newNode, currentNode.nextSibling);

If nextSibling- null, insertBeforeinserts a new node at the end of the node list.

+11
source

There is no direct method for inserting a node after a specific node, but there is a workaround:

var parent = currentNode.parentNode;
if(currentNode.nextSibling != null)
    parent.insertBefore(newNode,currentNode.nextSibling)
else
    parent.appendChild(newNode);
-1
source

Source: https://habr.com/ru/post/1719968/


All Articles