Reputation: 9198
Can I get in jQuery the list o childs (span) that belongs to a div? I mean the number of childs. I am generating a form with a few spans, and I need to know how many spans I have generated.
Upvotes: 3
Views: 1534
Reputation: 1337
This gives you the number of spans
var count = $("div").find("span").size();
This gives you the children as a new jQuery object, to loop through
var list = [];
list = $("div").children();
Upvotes: 2
Reputation: 218732
<div id="div1">
<span>s</span>
<span>s</span>
<span>s</span>
<span>s</span>
</div>
$(function(){
alert($("#div1 >span").size())
});
sample program here : http://jsfiddle.net/Bhrk2/
Upvotes: 2
Reputation: 165971
You can use the child selector, and the length
property:
var numberOfSpans = $("#someId > span").length;
Or, if you want to use this
for example, you can use the children
method:
var numberOfSpans = $(this).children("span").length;
Note that both of the snippets above give you the number of direct children span
elements. They won't count further descendants. If you want to do that, you can remove the >
character, or use find
instead of children
.
Upvotes: 6