GFL GFL - 4 months ago 17
Javascript Question

Loop Through All Elements that Meet Criteria

In vanilla JS, I'm trying to set a property for all "li"s that have certain parents under a specific class.

Basically if it meets ".qa ul li" then set the tabindex to 0.

Right now I'm using:

for(var i = 0; i < document.getElementsByTagName('li').length; i++){
if(????) document.getElementsByTagName('li')[i].tabIndex = 0;
}


My problem is I don't know how to see if that specific "li" is under a a "ul" under a "qa" class.

And if I were to get it, would a different approach be better? I have a lot of "li"s and not all meet my criteria.

Answer Source

Instead of getElementsByTagName(), you can use querySelectorAll():

var elements = document.querySelectorAll('.qa ul li');

for(var i = 0; i < elements.length; i++){
    elements[i].tabIndex = 0;
}

This will select only the <li> elements that you're looking for - no need for conditional logic.

I've also combined your repeated DOM searches into one variable. Instead of searching the DOM to initialize the for and then for each subsequent iteration, you only need one DOM search.


Example:

var elements = document.querySelectorAll('.qa ul li');

for (var i = 0; i < elements.length; i++) {
  elements[i].style.color = 'red';
}
<div class="qa">
  Parent has QA class:
  <ul>
    <li>TEST</li>
    <li>TEST</li>
    <li>TEST</li>
  </ul>
</div>


<div>
  Parent does not have QA class:
  <ul>
    <li>TEST</li>
    <li>TEST</li>
    <li>TEST</li>
  </ul>
</div>