jquery count li elements inside ul -> length?

后端 未结 10 1022
有刺的猬
有刺的猬 2020-12-29 17:42

If a ul has more than one li-element inside of it, something should happen, otherwise not!

What am I doing wrong?

if ( $(\'         


        
相关标签:
10条回答
  • 2020-12-29 18:39

    Make the following change:

    console.log($("#menu li").length);
    
    0 讨论(0)
  • 2020-12-29 18:41

    Another approach to count number of list elements:

    var num = $("#menu").find("li").length;
    if (num > 1) {
      console.log(num);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul id="menu">
      <li>Element 1</li>
      <li>Element 2</li>
      <li>Element 3</li>
    </ul>

    0 讨论(0)
  • 2020-12-29 18:46

    You have to count the li elements not the ul elements:

    if ( $('#menu ul li').length > 1 ) {
    

    If you need every UL element containing at least two LI elements, use the filter function:

    $('#menu ul').filter(function(){ return $(this).children("li").length > 1 })
    

    You can also use that in your condition:

    if ( $('#menu ul').filter(function(){ return $(this).children("li").length > 1 }).length) {
    
    0 讨论(0)
  • 2020-12-29 18:48
    alert( "Size: " + $("li").size() ); 
    

    or

    alert( "Size: " + $("li").length );
    

    You can find some examples of the .size() method here.

    0 讨论(0)
提交回复
热议问题