If you fiddle with tag string, for example by putting space between ><, the effect is different.
<!DOCTYPE html>
<head><title>insertBefore error</title></head>
<body>
<div id='myElement'>above this div 3 elements should be inserted
but actually only 2 are, text2 is missing</div>
<script type="text/javascript">
referenceTag = document.getElementById('myElement');
var newElement = document.createElement('div');
newElement.innerHTML = '<div>text1</div><pre>text2</pre><p>text3</p>';
for (i=0; i<newElement.childNodes.length; i++) {
alert(newElement.childNodes[i].tagName);
//if you comment-out following line there are 3 alerts but otherwise only two.
referenceTag.parentNode.insertBefore(newElement.childNodes[i],referenceTag);
}
</script>
</body>
When you call
insertBeforeyou move the node so it becomes a child ofreferenceTag.parentNode. At this point it is no longer a child ofnewElementsonewElement.childNodesshrinks by one.You then increment
i, so you keep skipping elements.i.e.
You probably want:
The effect is actually the same, but harder to see. Inserting spaces means that instead of having a data structure along the lines of:
You have:
Since you skip every other node, and every other node is a text node consisting entirely of white space, you can’t see the effect.