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?

asked Oct 13, 2009 at 11:22

2 Answers 2

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.1m201 gold badges2k silver badges2k bronze badges
answered Oct 13, 2009 at 11:27
Sign up to request clarification or add additional context in comments.

3 Comments

I hate this syntax, but this is the only way. +1
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.
@Gumbo, perhaps it's worth updating this as per crescentfresh's comment?
-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);
answered Oct 13, 2009 at 11:32

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.