简体   繁体   中英

JQuery - How do I count the number of elements selected by a selector?

I am using $().fadeOut() to fade items out in a list ( < li> < /li>). When the list is empty I wish to hide a parent object.

I plan on doing this by checking in my trigger event that fades the list if the count of the objects is 0 then hide the parent element. I can use the fadeOut callback to remove the elements if necessary.

The to the point question: How do I select li tags inside a ul and then get the total count of them using jquery?

Like this:

$('ul > li').length

A more elegant way to do it would be to write

$('ul:empty').fadeOut();

If the ul is not empty, the selector won't match anything, and the code will do nothing.

You may need to write

$('.SomeContainer:has(ul:empty)').fadeOut();

use .length

$('ul li').length // gives you back all li's in your ul
$('ul > li').length // give just the first children li's

so in order to hide your parent you can use it this way:

elements = $('ul > li')

if (elements.length) {
   elements.fadeOut()
}else{
   elements.parent().fadeOut()
}

Simply use .length against the jQuery collection.

var $elements = $('ul#myUlElement').children('li');
alert($elements.length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM