admin管理员组

文章数量:1391975

Here's how the HTML markup looks like

<ul>
  <li>red</li>
  <li>green</li>
  <li>
  <ul>
       <li>banana</li>
       <li>pineapple</li>
       <li>peanut</li>
  </ul>
  </li>
  <li>blue</li>
  <li>
  <ul>
       <li>sun</li>
       <li>mars</li>
       <li>earth</li>
  </ul>
  </li>
  <li>orange</li>
</ul>

how do I count direct children (<li>) in this list? (items containing red,green,blue,orange) ?

Here's how the HTML markup looks like

<ul>
  <li>red</li>
  <li>green</li>
  <li>
  <ul>
       <li>banana</li>
       <li>pineapple</li>
       <li>peanut</li>
  </ul>
  </li>
  <li>blue</li>
  <li>
  <ul>
       <li>sun</li>
       <li>mars</li>
       <li>earth</li>
  </ul>
  </li>
  <li>orange</li>
</ul>

how do I count direct children (<li>) in this list? (items containing red,green,blue,orange) ?

Share Improve this question edited May 19, 2012 at 18:00 Stephane asked May 19, 2012 at 17:41 StephaneStephane 5,08610 gold badges53 silver badges86 bronze badges 2
  • 3 First, before asking this question, correct your HTML. A ul is not a valid child of another ul element. Wrap the child ul elements in li elements (which are the only valid children of a ul or ol). – David Thomas Commented May 19, 2012 at 17:48
  • 1 possible duplicate of Select all li's but not children -- please use the search before you ask a new question. See also How can I count the number of children?. – Felix Kling Commented May 19, 2012 at 18:11
Add a ment  | 

3 Answers 3

Reset to default 4

Try this:

$('ul > li').length;

'ul > li' selector point only first level of children i.e direct children for all ul.

or

$('ul').children().length; 

If your code is string variable like

var html = '<ul><li>.....';

Then

$('ul > li', $(html)).length;

NOTE: Above code will find all li

To find only first level of li use:

$('ul:not(li > ul)').children().length;

You can also use:

$('ul:not(li > ul) > li').length

For html variable string:

$(html).children('ul > li').length;
var ul = document.querySelector('ul');
var count = 0;
for (var ch = ul.firstChild; ch; ch = ch.nextSibling)
  if (ch instanceof HTMLLIElement) count++;

Use this:

$("ul > li").length

Other way:

$("ul").children().length

In JQuery documentation you can also find size() method to get the number of elements. However, it is better to use length, since it is simply faster.

The first ul element can be taken by :first selector. Another way is to set the concrete <ul> element ID, and address it with #element_id selector.

DEMO: http://jsfiddle/xDYn9/

本文标签: javascriptcount direct children in html listStack Overflow