Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the <a> tags inside div + childs

I have a problem regarding to jQuery. I need to count the amount of <a> tags within a div. Now this can easilly be done by using $('.classOfDiv > a').size();. But I need to count the a's within a couple of childs of classOfDiv.

Ex.

<div class="classOfDiv">
    <div class="div1">
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
    </div>
    <div class="div2">
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
    </div>
    <div class="div3">
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
    </div>
    <div class="div4">
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
        <a href="" class="link">Link</a>
    </div>
</div>

$('.classOfDiv > a').size(); With the result of 12

Can this be done?

Thanks in advance!

like image 257
Guido Visser Avatar asked Aug 24 '12 12:08

Guido Visser


2 Answers

Just remove the > from the selector in order to get all a descendants of .classDiv, not just the direct ones:

$(".classOfDiv a").length
like image 98
João Silva Avatar answered Sep 19 '22 09:09

João Silva


The .classOfDiv > a selector will only get you the <a> tags which are direct descendants of a <div class="classOfDiv">, so you'll need to change your code to:

$('.classOfDiv a').length;

Notice the lack of > direct descendant selector.

like image 28
Matteo Tassinari Avatar answered Sep 20 '22 09:09

Matteo Tassinari