Doug Fir Doug Fir - 2 months ago 15
Javascript Question

querySelector() where display is not none

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;"?

Answer

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

Comments