13

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 ?
Arun Bertil
  • 4,598
  • 4
  • 33
  • 59
spiderman
  • 1,565
  • 2
  • 16
  • 37

4 Answers4

37

You can use :visible to get element which are visible.

$(".highlight:visible").length
Adil
  • 146,340
  • 25
  • 209
  • 204
8

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

dimitrisk
  • 774
  • 9
  • 15
5

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
       }
    });
Somnath Kharat
  • 3,570
  • 2
  • 27
  • 51
0

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.

W.M.
  • 589
  • 1
  • 6
  • 13