How to count li which does not have ul?

前端 未结 3 714
野趣味
野趣味 2021-02-15 00:39

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.

&l         


        
3条回答
  •  名媛妹妹
    2021-02-15 01:08

    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.

提交回复
热议问题