Search code examples
javascriptcss-selectorshtml2canvas

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?


Solution

  • 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'))