'jquery find element with class and style display:block
I am retrieving the number of "found" elements (these elements have the .highlight class) with this simple jQuery snippet:
$(".highlight").length
But now my problem is that some elements are hidden, via style="display: none;"
Now, How can I get the number of elements highlighted AND displayed?
Something like:
$(hasClass 'highlight' AND has style 'display: block'). length ?
Solution 1:[1]
One way is to use :visible jQuery pseudo selector as Adil mentioned.
A common pitfall is that if the element with class .highlight is nested to a container which is hidden then you wont be able to get it even though that element has display: block
Instead you could use css regex as follows:
$('.highlight[style*="display: block"]')
A common pitfall is that you need to know exactly how the rule is written. If there is no space before block like so: display:block instead of display: block you wont be able to get the element either.
A way to overcome this is to search only for the term block in the styles like so:
$('.highlight[style*="block"]')
Solution 2:[2]
U can also do by using css to see the element has css display="none" or display="block"
$(".highlight").each(function(){
if($(this).css("display")=="block"){
//Your code here
}
});
Solution 3:[3]
Here is the pure JS version:
Array.from(document.querySelectorAll('.one')).filter(s =>
window.getComputedStyle(s).getPropertyValue('display') != 'none'
);
Returns all elements with class name .one and attribute display: block.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dimitrisk |
| Solution 2 | |
| Solution 3 | W.M. |
