How to find the number of elements from child to parent with jquery?

I have a little problem when I need to count the level of nesting elements. The problem is that a parent can contain multiple children, and children can have their own children.

Please see where I want to start the countdown (marked with the 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 tried a couple of things to get a score of 3.
For example, my last attempt:

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

This one obviously returns 6 tho for counting all child_sets.

How to read child_set elements from the initial place to main_set , taking into account only nesting. So basically in my example, how to get score 3?

+2
source share
4 answers

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

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

Also see this example .

+6
source

If you want to read everything child_set , starting with a div that says I start here! , you would do the following:

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

This will give you 3 . Added 1 because your div with text I start here! also has a child_set class.

Documentation:

+1
source

You need to call stopPropagation or to call parent events because they have the same child_set class.

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

Working demo

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

+1
source

use .children() instead of .find()

clearly stated here

The .children () method differs from .find () in that only .children () moves one level down the DOM tree, while .find () can move down several levels to select descendant elements (grandchildren , etc.).

0
source

Source: https://habr.com/ru/post/1211322/


All Articles