Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - JQuery - How do I count the number of elements selected by a selector?

I am using $().fadeOut() to fade items out in a list ( < li> < /li>). When the list is empty I wish to hide a parent object.

I plan on doing this by checking in my trigger event that fades the list if the count of the objects is 0 then hide the parent element. I can use the fadeOut callback to remove the elements if necessary.

The to the point question: How do I select li tags inside a ul and then get the total count of them using jquery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like this:

$('ul > li').length

A more elegant way to do it would be to write

$('ul:empty').fadeOut();

If the ul is not empty, the selector won't match anything, and the code will do nothing.

You may need to write

$('.SomeContainer:has(ul:empty)').fadeOut();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...