jquery count li elements inside ul -> length?

后端 未结 10 1021
有刺的猬
有刺的猬 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:21

    Working jsFiddle

    Please use .size() function instead of .length and also specify li tag in selector.

    Change your code like.

    if ( $('#menu ul li').size() > 1 ) {
    
    0 讨论(0)
  • 2020-12-29 18:24

    Use $('ul#menu').children('li').length

    .size() instead of .length will also work

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

    Warning: Answers above only work most of the time!

    In jQuery version 3.3.1 (haven't tested other versions)

    $("#myList li").length; 
    

    works only if your list items don't wrap. If your items wrap in the list then this code counts the number of lines occupied not the number of <li> elements.

    $("#myList").children().length;
    

    gets the actual number of <li> elements in your list not the number of lines that are occupied.

    0 讨论(0)
  • 2020-12-29 18:34
    alert( "Size: " + $( "li" ).size() );
    
    alert( "Size: " + $( "li" ).length );
    

    Both .size() and .length return number of item. but size() method is deprecated (JQ 1.8). .length property can use for instead of size().

    also you can use

    alert($("ul").children().length);
    
    0 讨论(0)
  • 2020-12-29 18:35

    The correct syntax is

    $('ul#menu li').length
    
    0 讨论(0)
  • 2020-12-29 18:36

    If you have a dom object of the ul, use the following.

    $('#my_ul').children().length;
    

    A simple example

    window.setInterval(function() {
      let ul = $('#ul');                 // Get the ul
      let length = ul.children().length; // Count of the child nodes.
    
      // The show!
      ul.append('<li>Item ' + (length + 1) + '</li>');
      if (5 <= length) {
        ul.empty();
        length = -1;
      }
      $('#ul_length').text(length + 1);
    }, 1000);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <h4>Count of the child nodes: <span id='ul_length'>0</span></h4>
    <ul id="ul"></ul>

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