How to explain this FOR loop in Javascript?

Asked

Viewed 93 times

2

Can someone explain me how this loop works and because the last class "TG" also disappears?

<!DOCTYPE html>
<html>
<body>

Usando a classe atributo em JavaScript

Clicando no botão esconde todos os elementos com a nome da classe "cidade".
<div style = "margin-top: 20px"></div>

<div><button onclick="esconde()">Esconde</button></div>

<h2 class="cidade">London</h2>
<p>São Paulo é a capital de São Paulo.</p>

<h2 class="cidade">Paris</h2>
<p>Paris é a capital da França.</p>

<h2 class="cidade">Tokyo</h2>
<p>São Luís é a capital do Maranhão.</p>

<h2 class="cidade">TG</h2>
<p>Tokyo é a capital do Japão.</p>

<script>
function esconde() {
  var x = document.getElementsByClassName("cidade");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
}
</script>

</body>
</html>

  • 1

    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.

  • 3

    Why do you think the last item with the class should NOT disappear?

5 answers

5


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!

  • I understood yes Leandro, yours was the most complete explanation I never expected to receive. Are you professor rs? My confusion was because I thought the excerpt x.lenght was counting the characters of each element of the 'city' classes'.

  • 1

    No am not prof yet kk, sometimes I give a lost in programming too, it’s normal happens, success ae! :)

3

You have a button that has onclick="esconde()" that is, when you click it performs the function esconde()

The function esconde in turn has a getElementsByClassName, notice that it is a getElements in the plural, that is, it takes ALL elements with calss="cidade", that’s right ByClassName (could be too getElementById, that’s getElement in the singular, since Ids Pressupions that are unique, have no more than one, then it is singular getElement), no matter if it is a tag h2 or div

inserir a descrição da imagem aqui

So document.getElementsByClassName("cidade"); takes any element with the class cidade

The for (var i = 0; i < x.length; i++) will create a loop by index, where you will count from the index element 0 and see how many elements with the city class exist (x.length) and then as long as this element index number is less than the total amount of elements with the class it will erase one by one until it completes all (i++)

  • 1

    Perhaps all his doubt comes even from not knowing that the first index is zero. I closed the question while it is not clarified.

  • @bfavaretto no problem Favaretto, if he does not say what he expected and what happened that he did not understand it is difficult even to give an answer. I wrote, but you can see that I myself voted to close rss :D

  • Yeah, I just went to see after I closed up that it was you :)

0

The getElementsByClassName("cidade") returns all elements that have the CSS class .cidade which in this case are the headers (h2). So the is assigns the property display = none to these elements, making the h2 no longer be shown

0

Are you adding to x all the elements that have the class "city" (the getElementsByClassName("city") does this) and then goes through x with this is, making all the element that contains the city class be hidden, because for each item is assigned the display="None". The element TG disappears because it also has the city class

0

Basically, it’s not just the "TG" that goes missing, but all the <h2> containing class="cidade". When the "Hide" button is clicked, its script interprets all elements containing the "city" class and stores them in an array on the line:

 var x = document.getElementsByClassName("cidade");

which is subsequently iterated in for. That one for executes so that it reads all the elements stored in the array, one by one, adding the property style.display = "none"; in them, causing the elements to "disappear".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.