简体   繁体   中英

How to count li which does not have ul?

Hi I want to count LI which does not have the UL , for the first level only, but when I count this it shows size 4 instead of 2, its count the inner LI also.

<div class="navigation-container">
    <ul class="first-level">
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a>
        <ul>
          <li><a href="#">Link2.1</a></li>
          <li><a href="#">Link2.2</a>
            <ul>
                <li><a href="#">Link 2.2.1</a></li>
            </ul>
          </li>
        </ul>
      </li>
      <li><a href="#">Link </a></li>
    </ul>  
  </div>

jQuery for this.

jQuery(document).ready(function(){

  var nosubnav = jQuery('.first-level li:not(:has(ul))');
  var nosubnavsize = jQuery('.first-level li:not(:has(ul))').size();
  jQuery(nosubnav).css('border' , '1px solid red');
  alert('List item which does not have submenu  '+nosubnavsize);

});

Link for the testing link text on JSBin,

thanks

You can use the child selector > to target only child elements directly under the parent.

jQuery(document).ready(function(){

  var nosubnav = jQuery('.first-level > li:not(:has(ul))');
  var nosubnavsize = jQuery('.first-level > li:not(:has(ul))').size();
  jQuery(nosubnav).css('border' , '1px solid red');
  alert('List item which does not have submenu  '+nosubnavsize);

});

This will return the count of 2. You can also optimise this slightly by reusing your stored selection of the target li (stored in nosubnav ):

jQuery(document).ready(function(){

  var nosubnav = jQuery('.first-level > li:not(:has(ul))');
  nosubnav.css('border' , '1px solid red');
  alert('List item which does not have submenu  '+nosubnav.length);

});

This will cut out the overhead of querying the DOM a second time.

Not sure if I'm reading right, but ..

$('ul.first-level > li:not(:first)').length

Returns 2 for me ( see demo )

$('.first-level > li:not(:has(ul))').size()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM