Neophyte Neophyte - 5 months ago 8
Javascript Question

Need to click Each li Element without affecting parent

I have HTML Structure like

<ul>
<li><a></a>
<ul>
<li><a></a>
<ul>
<li><a></a>
<ul>
<li><a></a></li>
</ul>
</li>
</ul>
</li>
</ul>





I want to add 'active' class for relevent 'a' Element when corrosponding li clicked.

Answer

Use children(), since you only want to select the direct child

$('li').click(function(){
   $(this).children('a').addClass('active')
})

or

$('li').click(function(){
   $('>a', this).addClass('active')
})