skip to Main Content

How to select all DOM elements that have a certain class but also have certain CSS attribute value using JavaScript?
For example, I want to select all the elements that have class "date" but have a display: none CSS attribute.
I know it has something to do with querySelector / querySelectorAll but I am unable to find such example (all the examples I stumbled upon either select by class or by CSS attribute but not by both).

2

Answers


  1. you can do this by combining the class selector with the attribute selector in the querySelector(All) method. Here is how you can select all elements with the class date and a CSS attribute display: none for example.

    const elements = document.querySelectorAll('.date[style*="display: none"]');
    
    Login or Signup to reply.
  2. I don’t know if you can do this with querySelector/querySelectorAll, but you can use this method:

    function select(classname, property, value) {
      var elements = [];
      var classes = document.getElementsByClassName(classname);
      for (var i = 0; i < classes.length; i++) {
        if (classes[i].style[property] == value) {
          elements.push(classes[i])
        }
      }
      return elements;
    }
    
    console.log(select("date", "display", "none"));
    <html>
    <body>
      <div style="display:none" class="date">Date1</div>
      <div class="date">Date2</div>
      <div style="display:none" class="date">Date3</div>
      <div class="date">Date4</div>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search