DanielX2010
DanielX2010

Reputation: 1908

selecting all elements of a class within elements of given id

My HTML code looks something like

<div id="partA">
    <div class="myClass typeA"> blabla </div>
    <div class="myClass typeA"> blabla </div>
    <div class="myClass typeA"> blabla </div>
    <div class="myClass typeB"> blabla </div>
</div>

<div id="partB">
    <div class="myClass typeA"> blabla </div>
    <div class="myClass typeA"> blabla </div>
    <div class="myClass typeA"> blabla </div>
    <div class="myClass typeB"> blabla </div>
</div>

I want to use javascript to count the number of elements of class myClass, but only the one that are within #partA.
When I use
$(".myClass").size()
I get 8 as result (it counts all the elements from both partA and partB).
When I use
$(".myClass.typeA").size()
I get 6 (it gets all myClass and typeA elements, from both parts)
But when I use
$("#partA.myClass").size()
I get 0.
Apparently, that javascript command only looks for elements that have both id=partA and class=myClass. Is it possible to reformulate that command in order to count the number of myClass class that are contained within the elements with id=partA?

Thanks a lot!

Upvotes: 0

Views: 191

Answers (1)

Coin_op
Coin_op

Reputation: 10718

You're missing a space in one of your selectors. Try:

$("#partA .myClass").size()

Alternatively you could do:

$('#partA').find('.myClass').length;

Or

var partA = $('#partA');
$('.myClass', partA).length;

Upvotes: 4

Related Questions