Denees
Denees

Reputation: 9198

CSS child selector with jQuery

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

Answers (4)

Stefan Konno
Stefan Konno

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

Shyju
Shyju

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

jValdron
jValdron

Reputation: 3418

You can get this by doing so:

$('#div-id span').size();

http://api.jquery.com/size/

Upvotes: 3

James Allardice
James Allardice

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

Related Questions