0

First of all, I am really awful at javascript, I am just trying to prepare for my exam the day after tomorrow. Why does this code snippet:

var colection=document.getElementsByClassName("old");
for(var i=0; i<colection.length;i++)
colection[i].className="new";

Don't work?

Also, why does this:

var colection=document.querySelectorAll(".old");
for(var i=0; i<colection.length;i++)
colection[i].className="nou";

or this:

var vector=[];
var colectie=document.getElementsByClassName("vechi");
for(var i=0;i<colectie.length;i++)
vector[i]=colectie[i];
for(var i=0;i<vector.length;i++)
vector[i].className="nou";

Work fine? Our teacher just told us the first one is not correct, but didn't tell us exactly why.

Also, if the first one does not work, why does this:

<script>
window.onload=function()
{
var
list=document.getElementsByTagName("p");
alert("There are"+list.length+" paragraphs");
for(var p of list)
{p.style.color="red";}
}
</script>
</head>
<body>
<h1>Colectie</h1>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
<div>This is a div</div>
</body>

work?

I really can not figure out the differences... Thank you

1 Answers1

2

getElementsByClassName returns a live HTMLCollection meaning it will automatically update itself. So by changing an elements className it gets removed from the list, reducing the length making it skip elements.

var colection=document.getElementsByClassName("old");
for(var i=0; i<colection.length;i++)
colection[i].className="new";

querySelectorAll is more like a snapshot at the moment of execution. It does not update itself. This means the length doesn't get affected and it can change every elements className.

var colection=document.querySelectorAll(".old");
for(var i=0; i<colection.length;i++)
colection[i].className="nou";

This example turns your live HTMLCollection into an array. Removing the problem of the length changing, therefore skipping elements. They still get removed from the colectie but since your looping over the vector it doesn't effect the output.

var vector=[];
var colectie=document.getElementsByClassName("vechi");
for(var i=0;i<colectie.length;i++)
vector[i]=colectie[i];
for(var i=0;i<vector.length;i++)
vector[i].className="nou";

Eventhough getElementsByTagName also returns a live HTMLCollection. In this loop your not changing the tag so the length of the collection will also not change, giving you the output you expect.

var list=document.getElementsByTagName("p");
alert("There are"+list.length+" paragraphs");
for(var p of list) {
  p.style.color="red";
}
Reyno
  • 6,119
  • 18
  • 27