7

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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Leo Messi
  • 5,157
  • 14
  • 63
  • 125

5 Answers5

14

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'))
Andy
  • 61,948
  • 13
  • 68
  • 95
Mamun
  • 66,969
  • 9
  • 47
  • 59
3

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();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

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'; })
Chris Li
  • 2,628
  • 1
  • 8
  • 23
0

Use method querySelectorAll() See https://www.w3schools.com/jsref/met_document_queryselectorall.asp

You are getting error because querySelectorAll returns an array.Iterate over it and then use style.display

Aagam Jain
  • 1,546
  • 1
  • 10
  • 18
0

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');
})