3

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 method to Ins. after the current node?

Harish
  • 1,617
  • 4
  • 21
  • 20

2 Answers2

11

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Gumbo
  • 643,351
  • 109
  • 780
  • 844
-1

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);
jerjer
  • 8,694
  • 30
  • 36
  • No, that's incorrect. `insertBefore` with `null` as the reference element inserts at the *end* of the parent node (e.g., it's the same as `appendChild`). No need at all for the check. – T.J. Crowder Apr 23 '12 at 21:51