Why does replaceChild () behave strangely when replacing one kind of element with another?

I am relatively new to javascript and found an interesting behavior that I cannot explain today. I have a custom <hr>(with image) on a website that weirdly displays in IE7 and below. To overcome this, I wanted to use replaceChild()in combination with getElementsByTag(). Initially, I was just trying to iterate over the list, so that:

var hrules = document.getElementsByTagName('hr');
for (var i=0; i < hrules.length; i++) {

   var newHrule = document.createElement("div");
   newHrule.className = 'myHr';

   hrules[i].parentNode.replaceChild(newHrule, hrules[i]);

   document.write(i);
}

However, this does not work: in fact, it receives only half the elements, skipping all the rest. Printing igives half-integer values ​​of the actual number of elements <hr>in the document (for example, if there are 7 <hr/>elements, it prints 4 ). On the contrary, the following works

var hrules = document.getElementsByTagName('hr');
var i = 0;
while (i < hrules.length) {

   var newHrule = document.createElement("div");
   newHrule.className = 'myHr';

   hrules[i].parentNode.replaceChild(newHrule, hrules[i]);

   document.write(i);
}

i , hrules (, , 0, ), hrules . , while while(true) - , <hr> , , , ( 0s).

, . .. p div, span p .. p p, div div .., .

, (w3schools, Google, ..) .

? -, , , - replaceChild() ? -, ?

+5
2

document.getElementsByTagName - HR - , . HR , .

, hrules.length . , , .

+6

, , , - (, @Pav ) .

var hrules = document.getElementsByTagName('hr');

/* Each repetition will delete an element from the list */
while (hrules.length) {
   var newHrule = document.createElement("div");
   newHrule.className = 'ieHr';

   /* Each iteration, change the first element in the list to a div
    * (which will remove it from the list and thereby advance the "head"
    * position forward. */
   hrules[0].parentNode.replaceChild(newHrule, hrules[0]);
}

, , hrules . (. Matthew Wilson answer). , div, , . , 0.

, , , .

+4

All Articles