简体   繁体   中英

Get to length of children elements for an element by tag name

I am trying to get length of li in my code which is a list under list.

 $(`ul.topnav > li`).each(function() { console.log($(this).children("ul li").length); }); 
 body { font-size: 14px; } 
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <ul class="topnav"> <li>Item 1 <ul> <li class="topnav1">Nested item 1</li> <li class="topnav1">Nested item 2</li> </ul> </li> <li>Item 2 <ul> <li class="topnav1">Nested item 1</li> <li class="topnav1">Nested item 2</li> <li class="topnav1">Nested item 3</li> </ul> </li> <li>Item 3 <ul> <li class="topnav1">Nested item 1</li> </ul> </li> </ul> 

But the length seems to print 0 for every element. However if I do this:

$(`ul.topnav > li`).each(function() {
  console.log($(this).children().children().length);
});

then it is printing correct ie 2,3,1.

But Can I get to nth children by tag name. What I am missing?

The issue is because children() is looking for child elements that match the ul li selector. This is not possible, as they can only be ul elements.

To fix this I'd suggest you use find() instead. If you specifically only want the first level of li elements you can use > ul > li as the selector.

 $(`ul.topnav > li`).each(function() { console.log($(this).find("ul li").length); }); 
 body { font-size: 14px; } 
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <ul class="topnav"> <li>Item 1 <ul> <li class="topnav1">Nested item 1</li> <li class="topnav1">Nested item 2</li> </ul> </li> <li>Item 2 <ul> <li class="topnav1">Nested item 1</li> <li class="topnav1">Nested item 2</li> <li class="topnav1">Nested item 3</li> </ul> </li> <li>Item 3 <ul> <li class="topnav1">Nested item 1</li> </ul> </li> </ul> 

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