jerz jerz - 2 months ago 7
HTML Question

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 every loop. Can anyone point out what im missing in the code please. Thank you
Here is my code:



function changeClass(){

for (i=0;i<3;i++) {
var list = document.getElementsByClassName("listing")[i];
list.style.color = "blue";
var values = document.getElementsByClassName("value");
document.write(i);
}
}

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

<ul id="groupList">
<li class="listing">First</li>
<li class="listing">First</li>
<li class="listing">First</li>
<li class="value"></li>
</ul>
<button id="change">change listing</button>




Answer

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.

function changeClass(){
   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);
<ul id="groupList">
<li class="listing">First</li>
<li class="listing">First</li>
<li class="listing">First</li>
<li id="value"></li>
</ul>
<button id="change">change listing</button>

Comments