简体   繁体   中英

Determine if a UL has 1 or more LI within

How can I use JavaScript to determine if a UL contains 1 or more LI's within?

Pseudo code

if('ul#items' has >= 1 LI){

Thanks,

With jQuery:

$('ul#items li').length >= 1

Without jQuery:

document.getElementById('items').getElementsByTagName('li').length >= 1

使用jQuery:

if( $('#items li').length >= 1 ){...

Use document.getElementById("items").childNodes.length and a number comparison operator. If your ul does contain other nodes than li , you will have to filter them.

In jQuery:

 $("#items").children("li").length

I guess you only want direct children, so don't use find().

if ($('ul#items').children('li').length) {
    // etc.
}

您可以使用:

$('ul#items li').length

If you're using jQuery

if($('ul > li').size()>0) {

} 

That will check that the UL element has more than 0 direct child li elements.

if ($('ul#items > li').length >= 1)

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