querySelector() where display is not none

懵懂的女人 提交于 2021-01-21 07:19:23

问题


I have a long list of <li> items I need to filter. I want the visible ones. Here's an example hidden one:

<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>

Those which are not hidden don't have a display visible attribute, they just don't have a style attribute at all.

This gives me the opposite of what I want:

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

How can I select based on style attribute does not equal or contain "display:none;"?


回答1:


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>



回答2:


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"])');



回答3:


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


来源:https://stackoverflow.com/questions/39813081/queryselector-where-display-is-not-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!