Hi, 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?
+9
A:
Just get the next sibling of the current node and insert the new node before that node:
currentNode.parentNode.insertBefore(newNode, currentNode.nextSibling);
Like noted in the comments, insertBefore
already inserts the new node at the end of the node list if there is no next sibling node.
Gumbo
2009-10-13 11:27:03
I hate this syntax, but this is the only way. +1
spudly
2009-10-13 12:10:55
Something neat is that only `currentNode.parentNode.insertBefore(newNode, currentNode.nextSibling)` is needed. If currentNode.nextSibling is `null`, the outcome is exactly that of the appendChild line anyway.
Crescent Fresh
2009-10-13 13:26:40
@Gumbo, perhaps it's worth updating this as per crescentfresh's comment?
J-P
2009-10-13 14:08:06
@crescentfresh: Thanks, didn’t know that.
Gumbo
2009-10-13 15:35:10
A:
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
2009-10-13 11:32:15