Aditya
Aditya

Reputation: 260

How to get length of elements with a certain css attribute?

If i have an html snippet

<div>
     <ul style="display:block">
         <li>A</li>
         <li>B</li>
     </ul>
     <ul style="display:none">
         <li></li>
         <li></li>
     </ul>
</div>

How to use jQuery to find the no. of ul elements in div with a css property of display: none? I know I can use $('div').children('ul').length but this returns all ul elements

Upvotes: 2

Views: 3346

Answers (3)

adeneo
adeneo

Reputation: 318182

You can filter for specific CSS values with a simple filter :

$('div ul').filter(function() {
    return this.style.display === 'none';
}).length

Upvotes: 3

Nemesis02
Nemesis02

Reputation: 292

You should be able to use the :visible tag to find all the visible lists and then do $('ul:visible').length or :hidden for the opposite to find the length.

Upvotes: 1

PSL
PSL

Reputation: 123739

You can use :hidden selector, if you want to get the length of hidden uls. It will take care of the ones with display:none set. And similarly you have the :visible selector as well.

$('div').children('ul:hidden').length

Elements can be considered hidden for several reasons:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Upvotes: 5

Related Questions