Reputation: 250
<ul>
<li class="solution device">
<a href="#">Device</a>
<ul>
<li>
<a href="#">Apple</a>
<ul>
<li><a href="#">iPad Air</a></li>
<li><a href="#">iPad Mini</a></li>
<li><a href="#">iPhone</a></li>
</ul><!-- // end 3rd level -->
</li>
</ul><!-- // end 2nd level -->
</li><!-- // end 1st level -->
</ul>
If a user clicks on any of the links I want to know what level it's in. So if you clicked iPhone it would be level = 3 (or 2 if it's indexed from of 0). I can hard code something but am looking for a dynamic solution that can work with any # of levels and no classes on the li or href. Any smart ideas? Thanks in advance.
Upvotes: 1
Views: 347
Reputation: 2975
You can do following:
$('ul#root_id').on('click', 'li', function(){
console.log($(this).parentsUntil('ul#root_id', 'li').length);
});
Here 'ul#root_id'
is your root ul element. And read about parentsUntil().
Upvotes: 1
Reputation: 388316
Try (Added an id top
) to the top ul
element
$('#top a').click(function(){
var $lis = $(this).parentsUntil('#top', 'li');
console.log($lis.length)
})
Demo: Fiddle
Upvotes: 2