JS loop and maintain index of parameters that meet condition Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JS loop and maintain index of parameters that meet condition without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a bunch of div‘s that I’m selecting by getElementsByClassName let’s call it:

let myDivs = document.getElementsByClassName('small-divs');

I need to set innerText conditionally to myDivs depending on whether each <div> in myDivs is style.visibility != 'hidden'

So I’m looping using a for loop and within the loop I have the condition checking for visibility:

for(let i=0; i < myDivs.length; i++){
  if(myDiv[i].style.visibility != 'hidden'){
    myDiv[i].innerText = letter + i; // letter is a user defined array of letters to use for 'rows'
  }
}

This is working as it should but my problem is that I need the i in letter + i to begin from 1 rather than from the element’s index that meets the condition. Here’s a pictorial of what I have:

This is before hiding any divs:

enter image description here

And here’s what I have after hiding some divs and running the above code. Notice that the inner text starts from the index that meets the conditions. For instance I need “row K” to start from K1 enter image description here

How can I achieve this? Seems like a small step I should do that I’m missing

Answer

Do you mean something like this? Use a counter which increments only when a non-hidden div is found

let number = 1;
for(let i=0; i < myDivs.length; i++){
  if(myDiv[i].style.visibility != 'hidden'){
    myDiv[i].innerText = letter + number; // letter is a user defined array of letters to use for 'rows'
    number += 1;
  }
}
We are here to answer your question about JS loop and maintain index of parameters that meet condition - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji