I have a long list of <li>
items I need to filter. I want the visible ones. Here’s an example hidden one:
JavaScript
x
6
1
<li style="display:none;"
2
<a href="https://www.example.com/dogs/cats/">
3
<img class="is-loading" width="184" height="245"
4
</a><span>dogscats</span>
5
</li>
6
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:
JavaScript
1
2
1
document.querySelectorAll('.newSearchResultsList li[style="display:none;"]')
2
How can I select based on style attribute does not equal or contain “display:none;”?
Advertisement
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, so you will want to include a selector for the space that may be normalized in.
JavaScript
1
5
1
var elements = document.querySelectorAll(
2
'.newSearchResultsList li:not([style*="display:none"]):not([style*="display: none"])'
3
);
4
5
console.log(elements);
JavaScript
1
6
1
<ul class="newSearchResultsList">
2
<li style="display:none;">hidden 1</li>
3
<li style="display:block;">visible 1</li>
4
<li style="display:none;">hidden 2</li>
5
<li style="display:block;">visible 2</li>
6
</ul>
If you want you could also select both these elements and any child elements.
JavaScript
1
4
1
const selector = '.newSearchResultsList li:not([style*="display:none"]):not([style*="display: none"])';
2
const elements = document.querySelectorAll(`${selector}, ${selector} *`);
3
4
console.log(elements);
JavaScript
1
6
1
<ul class="newSearchResultsList">
2
<li style="display:none;">hidden <i>1</i></li>
3
<li style="display:block;">visible <b>1</b></li>
4
<li style="display:none;">hidden <i>2</i></li>
5
<li style="display:block;">visible <b>2</b></li>
6
</ul>
Of course, these only work when selecting elements with inline styles.