Nom
Nom

Reputation: 11

for loop isn't working inside a class element

My codes should have shown 1 2 3 4 5 6 7 8 9 10 . But it is showing only 10. what is the error??But it works when I write (document.write(x);) . codes are given below

    for(x=0;x<=10;x++){

        document.querySelector(".for").innerHTML=(x+"</br>");

    }

Upvotes: 0

Views: 74

Answers (3)

Paulo R.
Paulo R.

Reputation: 15609

Here's what your loop is essentially doing:

 //sets .for's content to  0<br>
 document.querySelector(".for").innerHTML=(0+"</br>");

 //sets .for's content to  1<br>, erasing what was there before
 document.querySelector(".for").innerHTML=(1+"</br>");

 //sets .for's content to  2<br>, erasing what was there before
 document.querySelector(".for").innerHTML=(2+"</br>");

 ...

 //sets .for's content to  9<br>, erasing what was there before
 document.querySelector(".for").innerHTML=(9+"</br>");

Each cycle in the loop is setting the content to something new, overriding what was already there.

If instead, you want to add to what is already there then you should do something like:

for(x=0;x<=10;x++){
    document.querySelector(".for").innerHTML = document.querySelector(".for").innerHTML + ( x+"</br>"  );
}

BONUS:

Javascript offers a simplified way to 'adding to what is already there' with the += syntax. E.g:

a = a + 1;

could be written as:

a += 1;

In the same way:

a = a + 5;

... could be written as:

a += 5;

And in the same way:

document.querySelector(".for").innerHTML = document.querySelector(".for").innerHTML + ( x+"</br>"  );

... could be written as:

document.querySelector(".for").innerHTML += (x + "</br>");

So you could actually use that and simplify your code to:

for ( x=0; x<=10; x++ ) {
    document.querySelector(".for").innerHTML += (x + "</br>");
}

And while I'm at it, a little performance boost that could have an impact if you were doing a bigger loop:

const element = document.querySelector(".for");

for ( let x = 0; x <= 10; x++ ) {
    element.innerHTML += (x + "</br>");
}

Instead of querying the document for the same element each and every cycle of the loop, you query it once and store a reference to it before the loop, and refer to it in the loop.

Upvotes: 1

Vandesh
Vandesh

Reputation: 6894

You just missed appending data to the HTML. Instead of replacing the innerHTML, you can keep adding to it inside the loop like -

document.querySelector(".for").innerHTML+=(x+"</br>");

Run the code snippet below to check.

for(x=0;x<=10;x++){

        document.querySelector(".for").innerHTML+=(x+"</br>");

    }
<div class="for"></div>

Upvotes: 1

Aaron
Aaron

Reputation: 1737

You have to append the inner html and not override it. Otherwise only the last iteration is present.

for(x=0;x<=10;x++){
document.querySelector(".for").innerHTML += (x+"</br>");
}
<p class="for"></p>

Upvotes: 2

Related Questions