Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all elements containing a class with querySelector

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?

like image 938
Leo Messi Avatar asked Jan 28 '23 10:01

Leo Messi


2 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'))
like image 181
Mamun Avatar answered Jan 31 '23 21:01

Mamun


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();
like image 32
Rory McCrossan Avatar answered Jan 31 '23 21:01

Rory McCrossan