javascript - How to get length of elements with a certain css attribute? - Stack Overflow

admin2025-04-09  0

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

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

Share Improve this question edited Dec 3, 2013 at 19:32 ComFreek 29.4k18 gold badges107 silver badges157 bronze badges asked Dec 3, 2013 at 19:30 AdityaAditya 2605 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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.

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

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

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744128095a232555.html

最新回复(0)