Good at variable x
you have a value referencing the classes in html that is the class cidade
.
var x = document.getElementsByClassName("cidade");
Referring to these classes.
<h2 class="cidade">London</h2>
<h2 class="cidade">Paris</h2>
<h2 class="cidade">Tokyo</h2>
<h2 class="cidade">TG</h2>
Then already inside the ()
in the for
you have a variable i
receiving the value 0
this would be the initialization of for
.
for (var i = 0;)
Then you have, the variable i
is smaller than the x.length
that would be the condition.
for(var i= 0; i < x.length;)
That is to say the variable i
is less than the quantity of class cidade
?. In the html code within all h2
they have the same classes or there are 4 classes cidades
. So he does 0
is less than 4
if it is it executes the code snippet x[i].style.display = "none";
.
for(var i= 0; i < x.length;) {
x[i].style.display = "none";
}
Before the part .style.display = "none";
In that part x[i]
may seem confusing to you more often in Javascript when you access more than one element you always have to indicate which is the element. For example if this code did not exist the for
just to make it easier for you. If you wanted to change the color of the first h2
with class cidade
, then you would use document.getElementsByClassName("cidade")[0].style.color = 'red';
the [0]
is the first class so the color would be applied to the first h2
text-based London, if you put [1]
would be second class, if you put [2]
would be the third and so on. The Javascript starts counting from 0 and not 1. So back in the part x[i]
means nothing more, nothing less than the value of i
will represent the classes cidade
.
And then on i++
that operator ++
he is the increment operator he always increments +1 in the variable i
. You could use for example i = i + 1
or i += 1
or if you want to increment 2 by 2 I would use so i += 2
and so it goes.
for (var i = 0; i < x.length; i++) {
And that’s it, so summarizing the variable i
receives 0
. i
is less than the quantity(or length) of classes cidade
? if you run that code block that will disappear with the first element with the class cidade
and increments +1 on variable i
that has the value 0
(Becomes 1). then goes back to for
the variable i
(now i
has the value 1
increment) the number of classes cidade
is less than i
if executing the code that will disappear with the second element with the class cidade
and increments +1 on variable i
. And so you will perform until you reach a point that will be false
which is 4 is less than 4?. Logically not, then it is less than 4? false
, ae it for the for
.
I hope I understood!
You go through all the elements with the class city and hides them, it happens that the
header
text-based T2 also has the class city and therefore is hidden.– Caique Romero
Why do you think the last item with the class should NOT disappear?
– bfavaretto