arma
arma

Reputation: 4124

How to find element count from child to parent with jquery?

I have a slight issue where i need to count nest level of elements. Problem is that parent element can hold multiple child elements and child elements can have their own child elements.

Please see from where i want to start count (marked with text "I start here").

HTML:

<div class="main_set">
    <div class="child_set">
        <div class="child_set">
            <div class="child_set">I start here!</div>
        </div>
        <div class="child_set"></div>
    </div>
    <div class="child_set">
        <div class="child_set"></div>    
    </div>
</div>

I have tried couple things to get count 3.
For example my last attempt:

$(this).closest('.main_set').find('.child_set');

This one obviously returns 6 tho counting all child_sets.

How to count child_set elements from start place to main_set taking into account only nesting. So basically in my example how to get count 3?

Upvotes: 2

Views: 12941

Answers (4)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

You have to call stopPropagation or it'll call the parent events because they have the same class child_set.

 $('.main_set').on('click', '.child_set', function(e) {
        e.stopPropagation();
        console.log($(this).parents('.child_set').andSelf().length);
    });

Working demo

Look this other demo: Link
Here you can see that it works for any div.

Upvotes: 1

scessor
scessor

Reputation: 16125

You can use parents() from this to find all parents (with a special selector); for the length you have to add one for the current.

alert($(this).parents('.child_set').length + 1);

Also see this example.

Upvotes: 8

Blaster
Blaster

Reputation: 9080

If you want to count all child_set starting from div which says I start here!, you would do this:

$(this).parents('.child_set').length + 1

This would give you 3. The 1 is added because your div with text I start here! has also child_set class.

Documentation:

Upvotes: 1

xkeshav
xkeshav

Reputation: 54074

use .children() instead of .find()

here clearly said

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

Upvotes: 0

Related Questions