Reputation: 15372
What is the best way to count elements of a particular class within another element?
I have the class of the parent element, but there are other elements with that class. So if for example I have an element that i get to like this:
$(document).on('click', '.countButton', function(){
var parent = $(this).parents('parentDiv');
});
How can I put that element into a selector to count it like this:
$('.parentDiv > .childDivs').length;
Is there someway to convert an element into a selector, or something that points to that element? If that makes sense..
Thanks!
Upvotes: 1
Views: 86
Reputation: 700272
Yes, you can use the parent element as context for the search:
$('.childDivs', parent).length
Which is the same as:
parent.find('.childDivs').length
Upvotes: 0
Reputation: 1438
Could you perhaps use:
document.querySelectorAll('.parentDiv > .childDivs').length
?
Upvotes: 0
Reputation: 4114
So after var parent = $(this).parents('parentDiv');
you have the element you want and you just want its children with a certain class? If so
parent.children('.childDivs').length;
For direct descendants or:
parent.find('.childDivs').length;
To find elements with the 'childDivs' class at any depth with parent
Upvotes: 2