JQuery - How do I count the number of elements selected by a selector?

后端 未结 3 442
名媛妹妹
名媛妹妹 2020-12-10 12:32

I am using $().fadeOut() to fade items out in a list ( < li> < /li>). When the list is empty I wish to hide a parent object.

I plan on doing this by checking i

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

    Like this:

    $('ul > li').length
    

    A more elegant way to do it would be to write

    $('ul:empty').fadeOut();
    

    If the ul is not empty, the selector won't match anything, and the code will do nothing.

    You may need to write

    $('.SomeContainer:has(ul:empty)').fadeOut();
    
    0 讨论(0)
  • 2020-12-10 12:41

    use .length

    $('ul li').length // gives you back all li's in your ul
    $('ul > li').length // give just the first children li's
    

    so in order to hide your parent you can use it this way:

    elements = $('ul > li')
    
    if (elements.length) {
       elements.fadeOut()
    }else{
       elements.parent().fadeOut()
    }
    
    0 讨论(0)
  • 2020-12-10 12:44

    Simply use .length against the jQuery collection.

    var $elements = $('ul#myUlElement').children('li');
    alert($elements.length)
    
    0 讨论(0)
提交回复
热议问题