Get all elements containing a class with querySelector

Viewed 18707

For changing some styles in a class I'm using querySelector():

el.querySelector('.fa fa-car').style.display = "none";

This works fine for one element but if there are more elements containing this class and I want to change the display to none for all of them, this command only deletes the first occurrence of it leaving the next ones untouched.

I tried to do it with querySelectorAll():

 el.querySelectorAll('.fa fa-car').style.display = "none";

But this one returns an error message:

html2canvas: TypeError: Cannot set property 'display' of undefined

any ideas about how to get all the elements containing a specific class and perform an operation on them?

5 Answers

The Element method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Use Document.querySelectorAll() to get all the elements. Then use forEach() to set the style in each element:

var elList = document.querySelectorAll('.fa.fa-car');
elList.forEach(el => el.style.display = "none");

Please Note: Some older version of IE (<8) will not support querySelectorAll(). In that case use

Array.from(document.querySelectorAll('.fa.fa-car'))

querySelectorAll() returns a collection of elements. To change their styling you need to loop through them.

Also note that your selector appears to be invalid. Given the FontAwesome class rules I presume you need to select by both classes. Try this:

Array.from(el.querySelectorAll('.fa.fa-car')).forEach(function() {
  this.style.display = "none";
});

Alternatively, as you've tagged the question with jQuery, you could just simplify all that to just:

$('.fa.fa-car').hide();

querySelector only select one element, to select all element you can use querySelectorAll

[].map.call(el.querySelectorAll('.fa fa-car'), n => { n.style.display = 'none'; })

You could do all your operation by iterating the occurence of this class and of course by help of some if clauses.

$('.fa.fa-car').each(function(){
     $(this).css('color','white');
})
Related