• Item 1
  • Item 2
  • Item 3and I use jQ...">

    Count <li> s in <ul> with jQuery

    I have a simple list:

    <ul id="cyclelist"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> 

    and I use jQuery to cycle through the list. The first problem is finding if the list has more than one item to start with. I expect this to work:

     var $list = $('#cyclelist'); if ($list.length > 1) { ... } 

    But length always returns 1. Is there a better way to find the length of a list using jQuery? Or I'm wrong?

    +4
    source share
    4 answers

    Try $('#cyclelist li').length

    The problem is that $ ('# cyclelist') has only one element - the unordered list as a whole. If you want to know the number of list items in your unordered list, you can simply add an additional β€œli” selector.

    +13
    source
     var $list = $('#cyclelist li'); alert($list.length); 

    Simply put: you got the number of ULs matching this selector.

    +2
    source

    Your selector selects a dom element with the id "list of loops", which is a single element (ul with this id). What you would like to do is select the li elements attached to this ul. For this you can do (as indicated)

      $ ('# cyclelist li')
    
    +2
    source
     $('#cyclelist') 

    uses a CSS selector for an element with id = "list of loops" and, therefore, returns a link to a single element / object to correctly; -)

    I think you probably meant

     $('#cyclelist li') 

    to return list items to a named item.

    Another jQuery-esque way to iterate over item collections is to use each, cf http://docs.jquery.com/Core/each

    +1
    source

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


    All Articles