I was reading w3schools and found this example:
<body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>length</b> property.</p>
<script type="text/javascript">
x=document.getElementsByTagName("p");
document.write("------<br />");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
document.write("------");
</script>
</body>
which works just fine.
Then I thought doing the same with jQuery with
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Demo Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="code.js"></script>
</head>
and then in the code.js file have
$(document).ready(function() {
x=document.getElementsByTagName("p");
document.write("------<br />");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
document.write("------");
});
But with the second example, using jQuery the page loads forever
and never prints the p tags innerHTML values.
Why is this?
calls to
document.writeafter document.ready rewrites the document. and single the return value ofdocument.getElementsByTagNameis a live list the list becomes empty.So what actually happens is that the document contains.
When the document is ready you call
x = document.getElementsByTagName("p");andxcontains an array of<p>elements. But this is a live list and reflects the live state of the document. So when<p>elements get removed the list gets updated automatically.You then call
document.writewith"-----<br/>"and this empties the document and replaces it with that. So the variablexnow contains 0<p>elements becuase there are 0 in the document.The for loop doesn’t run because
x.length === 0As mentioned this is broken because W3Schools gives you broken code.
I highly recommend you learn from the MDN
Live Example
A better way to achieve this with jQuery would be :
Live Example