Joel Eckroth
Joel Eckroth

Reputation: 2534

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,

Upvotes: 11

Views: 34668

Answers (7)

Jakub Roztocil
Jakub Roztocil

Reputation: 16252

With jQuery:

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

Without jQuery:

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

Upvotes: 39

veblock
veblock

Reputation: 1924

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

Upvotes: 1

Tom Dickinson
Tom Dickinson

Reputation: 382

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.

Upvotes: 1

Bergi
Bergi

Reputation: 665584

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().

Upvotes: 4

sazh
sazh

Reputation: 1842

You can use:

$('ul#items li').length

Upvotes: 2

j08691
j08691

Reputation: 208040

With jQuery:

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

Upvotes: 5

inhan
inhan

Reputation: 7470

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

Upvotes: 2

Related Questions