sansSpoon
sansSpoon

Reputation: 2185

Javascript function not working for multiple elements

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.

Upvotes: 0

Views: 151

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

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>

Upvotes: 0

DocMax
DocMax

Reputation: 12164

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.

Upvotes: 2

Related Questions