I am trying to modify the body section based on the tagName, using JavaScript. But my webpage is loading infinitely when I use insertBefore() method to insert a tag before the <h1> tag. This problem is not happening when I try to insert before some other elements. I am new to JS, please help me.
This is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Para 1</p>
<p>Para 2</p>
<h1 id="head1">Para 3</h1>
<p id="parax"></p>
<div id="div1">
<p>Hello</p>
</div>
<ul id="mylist1">
<li>Script</li>
<li>deep learning</li>
<li>software testing</li>
<li>Python programming</li>
<li>Database systems</li>
</ul>
<p id="firstp">I was supposed to be first.</p>
<input type="button" onclick="myFunc()">
</body>
<script type="text/javascript">
var cn=document.body.children;
for(var i=0;i<cn.length;i++){
if(cn[i].tagName=="DIV"){
var h1 = document.createElement("H1");
var text = document.createTextNode("h1 tag inserted");
h1.appendChild(text);
cn[i].appendChild(h1);
}
else if(cn[i].tagName=="UL"){
var lis= cn[i].childNodes;
for(var j=0;j<lis.length;j++){
if(lis[j].innerHTML=="Python programming")
lis[j].innerHTML="machine learning";
}
}
else if(cn[i].tagName=="H1"){
var p=document.createElement("P");
var text=document.createTextNode("New para inserted before");
p.appendChild(text);
document.body.insertBefore(p,cn[i]);
}
else
document.write();
}
</script>
</html>
At this line i am facing problem (I think so) :
document.body.insertBefore(p,cn[i]);
Because you with this line code:
document.body.insertBefore(p,cn[i]);
increase number of document.body.children and every time you insert child you and number of body children and you never not hit last index.
please add this to see:
document.body.insertBefore(p,cn[i]);
alert(document.body.children.length); // add this line after insertBefore
see every alert show the number of document.body.children was increase
Thanks to Mr @foad , I got the answer for my question. Actually the insertBefore() method is inside a for loop. So in every iteration, a new tag is added to the body and the length of the body increases by 1. This caused the infinite loading.
The correction is to add a break statement after the insertBefore method:
document.body.insertBefore(p,cn[i]);
break;
This terminates the loop after adding the <p> tag before <h1> tag.