Skip to content Skip to sidebar Skip to footer

Inserting An Element

Is there a method in Javascript to insert an element after the current node.I know there is a method which inserts an element before the current node of the XML.But is there a met

Solution 1:

Just get the next sibling of the current node and insert the new node before that node using insertBefore:

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

If nextSibling is null, insertBefore inserts the new node at the end of the node list.

Solution 2:

There is no direct method to insert 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);

Post a Comment for "Inserting An Element"