使用javascript在ul里面有多少个li

时间:2022-11-14 20:13:12

How can I know how many li there are inside in the first ul?

我怎么知道第一个ul里面有多少里面?

I know I can use .length, but I want just the number of first-ul

我知道我可以使用.length,但我只想要第一个ul的数量

<ul class="first-ul">
    <li>1</li>
    <li>2</li>
    <li>
        <ul class="second-ul">
            <li>2.1</li>
            <li>2.2</li>
        </ul>
    </li>
</ul>

http://jsfiddle.net/5oykbysk/

http://jsfiddle.net/5oykbysk/

3 个解决方案

#1


4  

Use > to get immediate children li:

使用>立即获得子女:

alert(number = $('ul.first-ul > li').length);

FIDDLE:

http://jsfiddle.net/5oykbysk/1/

http://jsfiddle.net/5oykbysk/1/

See JQUERY DOCS for details

有关详细信息,请参阅JQUERY DOCS

#2


4  

[].filter.call(
    document.getElementsByClassName('first-ul')[0].children, 
    function (el) {
        return el.nodeName === 'LI';
    }
).length

#3


3  

use jQuery child selector. Try this:

使用jQuery子选择器。尝试这个:

$('ul.first-ul > li').length

DEMO

DEMO

#1


4  

Use > to get immediate children li:

使用>立即获得子女:

alert(number = $('ul.first-ul > li').length);

FIDDLE:

http://jsfiddle.net/5oykbysk/1/

http://jsfiddle.net/5oykbysk/1/

See JQUERY DOCS for details

有关详细信息,请参阅JQUERY DOCS

#2


4  

[].filter.call(
    document.getElementsByClassName('first-ul')[0].children, 
    function (el) {
        return el.nodeName === 'LI';
    }
).length

#3


3  

use jQuery child selector. Try this:

使用jQuery子选择器。尝试这个:

$('ul.first-ul > li').length

DEMO

DEMO