jquery count li elements inside ul -> length?

后端 未结 10 1069
有刺的猬
有刺的猬 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条回答
  •  猫巷女王i
    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('
  • Item ' + (length + 1) + '
  • '); if (5 <= length) { ul.empty(); length = -1; } $('#ul_length').text(length + 1); }, 1000);
    
    
    

    Count of the child nodes: 0

    提交回复
    热议问题