Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: count of first level of li tags (exclude decendent ul > li tags)

HTML:

<ul id='top_nav'>
  <li><a href="">xxx</a></li>
  <li><a href="">xxx</a></li>
  <li><a href="">xxx</a></li>
  <li>
    <ul>
      <li><a href="">xxx</a></li>
      <li><a href="">xxx</a></li>
    </ul>
  </li>
  <li><a href="">xxx</a></li>
</ul>

Question:

How can I get the count of the first level of li tags? So in this example, the output would be 5, not 7.

like image 514
MacGyver Avatar asked Jan 20 '26 14:01

MacGyver


1 Answers

$("#top_nav > li").size() should do the trick.

This works because a selector akin to foo > bar selects the immediate children of foo that match bar. the size() function returns the number of entities selected.

like image 78
dangerChihuahua007 Avatar answered Jan 23 '26 04:01

dangerChihuahua007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!