querySelector() where display is not none

前端 未结 3 1215
独厮守ぢ
独厮守ぢ 2021-02-20 11:29

I have a long list of

  • items I need to filter. I want the visible ones. Here\'s an example hidden one:

  • 相关标签:
    3条回答
    • 2021-02-20 12:12
      • Use '.newSearchResultsList li' selector to select all the li elements
      • Use Array#filter over collection
      • Use getComputedStyle to get all styles associated with element
      • Return only those elements having style !== none

      var liElems = document.querySelectorAll('.newSearchResultsList li');
      var filtered = [].filter.call(liElems, function(el) {
        var style = window.getComputedStyle(el);
        return (style.display !== 'none')
      });
      console.log(filtered);
      <ul class="newSearchResultsList">
        <li style="display:none;">
          <a href="https://www.example.com/dogs/cats/">
            <img class="is-loading" width="184" height="245">
          </a><span>dogscats</span>
        </li>
        <li>
          <a href="https://www.example.com/dogs/cats/">
            <img class="is-loading" width="184" height="245">
          </a><span>Visible</span>
        </li>
      </ul>

      0 讨论(0)
    • 2021-02-20 12:25

      This whole thing is kind-of hacky, but you could use the :not() selector to invert your selection. Beware some browser normalize the style attribute, so you will want to include a selector for the space that may be normalized in.

      var elements = document.querySelectorAll(
          '.newSearchResultsList li:not([style*="display:none"]):not([style*="display: none"])'
      );
      
      console.log(elements);
      <ul class="newSearchResultsList">
          <li style="display:none;">hidden 1</li>
          <li style="display:block;">visisble 1</li>
          <li style="display:none;">hidden 2</li>
          <li style="display:block;">visisble 2</li>
      </ul>

      0 讨论(0)
    • 2021-02-20 12:35

      Try this:

      document.querySelectorAll('.newSearchResultsList li:hidden')
      

      or (EDIT: Based on style attribute.)

      document.querySelectorAll('.newSearchResultsList li[style*="display:none"]');
      

      or opossite

      document.querySelectorAll('.newSearchResultsList li:not([style*="display:none"])');
      
      0 讨论(0)
    提交回复
    热议问题