0

I'm trying to add an element after multiple selected elements. The problem is that it only seems to apply it to a single element. The code is in this fiddle.

<p id="1"></p>
<p id="2"></p>

<script>
function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

var errorNode = document.createElement("span");
errorNode.className = "error";
errorNode.innerHTML = 'You must specify a value';
var errorField = document.getElementById('1');
errorField.innerHTML = 'para 1';
insertAfter(errorField, errorNode);
errorField = document.getElementById('2');
errorField.innerHTML = 'para 2';
insertAfter(errorField, errorNode);

</script>

In this case it only adds it to the 2nd para. If you comment out the 2nd function call it correctly adds it to the first para. It is however successfully updating the para contents.

Any help appreciated in advanced.

2
  • Out of curiosity why have you created an alternate version of Node.insertBefore()? Commented Jul 8, 2015 at 5:44
  • It's to place the element after the one you want. I got it from: stackoverflow.com/questions/4793604/… Commented Jul 8, 2015 at 5:56

2 Answers 2

2

When you call Node.insertBefore the second time, it moves your errorNode from the first to the second paragraph. As stated on W3.org:

If the newChild is already in the tree, it is first removed.

If you want two error nodes, you need to create two, populate each with your text, and add each to its own paragraph.

Sign up to request clarification or add additional context in comments.

Comments

0

You are just creating 1 errorNode element, and moving it around in the dom when you are calling the insertBefore() each time.

Instead you need to create a new instance of the node, if you want to add it in different locations. You can create a clone of the node to do that like

function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

var errorNode = document.createElement("span");
errorNode.className = "ms-formvalidation";
errorNode.innerHTML = '<span role="alert">You must specify a value for this required field.<br></span>';
var errorField = document.getElementById('1');
errorField.innerHTML = 'para 1';
insertAfter(errorField, errorNode.cloneNode(true));
errorField = document.getElementById('2');
errorField.innerHTML = 'para 2';
insertAfter(errorField, errorNode.cloneNode(true));
<p id="1"></p>
<p id="2"></p>

1 Comment

Ahh, that makes sense. Good to know about the element cloning, Thanks!

Your Answer

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.