Determine if UL has 1 or more LIs inside

How can I use JavaScript to determine if UL contains 1 or more LIs inside?

Pseudo code

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

Thanks,

+6
source share
7 answers

Using jQuery:

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

Without jQuery:

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

Using jQuery:

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

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

In jQuery:

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

I think you only need direct children, so do not use find ().

+2
source

You can use:

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

If you are using jQuery

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

This will verify that the UL element has more than 0 direct children li.

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

Source: https://habr.com/ru/post/911819/


All Articles