Skip to content Skip to sidebar Skip to footer

Variable "i" Not Displaying In Javascript For Loop

I am trying to do some for loop practice and apply the blue color style to all 'listing' class with a click event. In addition to that, i also wanted to print the value of 'i' in e

Solution 1:

You have used document.write() function it may be override document HTML content you can use console.log() method for debugging variable. Also take element reference in one variable so it will make some faster execution. Change class="value" to id="value" because it only one element so identifier is good instead of class. Class refer to multiple element but id refer to only one element.

functionchangeClass(){
   var dom=document.getElementsByClassName("listing");
   var all_index=[]
   for (i=0;i<dom.length;i++) {
      var list =  dom[i];
      list.style.color = "blue";
      all_index.push(i);
      
   }
   document.getElementById("value").innerHTML=all_index.join(",");
      
}

document.getElementById("change").addEventListener("click", changeClass);
<ulid="groupList"><liclass="listing">First</li><liclass="listing">First</li><liclass="listing">First</li><liid="value"></li></ul><buttonid="change">change listing</button>

Solution 2:

you need to add a listener to invoke chageClass function

document.getElementById("change").addEventListener('click',changeClass,true);

Here i am going to indicate the reason of the problem in for loop :

inside your forloopwhen i==0;

document.write(i) will elimenate all the elements in your document and will print 0 in you document if everything is ok.

when i==1 in for loop :

the following line will become invalid because there will be no element holding the class "listing" .All other elements are eliminated from document .Now it will eliminate "0" form document and print "1" in document.and it will go on and on as long as the for loop goes on .

var list =  document.getElementsByClassName("listing")[i]; 

use document.body.innerHTML instead if you want to print in document:

functionchangeClass(){

   for (i=0;i<3;i++) {
      var list =  document.getElementsByClassName("listing")[i];

      list.style.color = "blue";
      var values = document.getElementsByClassName("value");
     document.body.innerHTML+='<br>'+i+'<br>';
   }

}
  document.getElementById('change').addEventListener('click',changeClass,true);

Post a Comment for "Variable "i" Not Displaying In Javascript For Loop"