Reputation: 213
I want to add a specific class to next parent element (li) of link. For example I have active class on 'Home" tab but same time I also need 'new-class' to 'About' li. Here is my markup
This is working for static class but when active class on link added dynamically, This is not working.
I tried this but not able to make working
$('li a').click(function() {
if ($(this).hasClass('active')) {
$(this).parent().next().addClass('active');
}
else{
$(this).parent().next().removeClass('active');
}
});
<ul>
<li><a class="active" href="">Home</a></li>
<li class="new-class"><a href="">About</a></li>
<li><a href="">Service</a></li>
<li><a href="">Portfolio</a></li>
<li><a href="">Contact</a></li>
</ul>
Upvotes: 0
Views: 941
Reputation: 1322
I think this is what you want :
$('li a').click(function(e) {
e.preventDefault();
$(this).closest('ul').find('a.active').removeClass('active');
$(this).closest('ul').find('li.new-class').removeClass('new-class');
$(this).addClass('active');
$(this).parent().next().addClass('new-class');
});
.active{ color:red; }
.new-class a { color:blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a class="active" href="">Home</a></li>
<li class="new-class"><a href="">About</a></li>
<li><a href="">Service</a></li>
<li><a href="">Portfolio</a></li>
<li><a href="">Contact</a></li>
</ul>
Upvotes: 2
Reputation: 67748
If I understand you correctly (on clicking a
having class active
add class new-class
to subsequent li
?), this should work:
$('.tab a').click(function() {
if ($(this).hasClass('active')) {
$(this).parent().next().addClass('new-class');
} else{
$(this).parent().next().removeClass('new-class');
}
});
Upvotes: 0
Reputation: 1616
$(this).parent().next().addClass('active');
This will first get to the li of the anchor being clicked. Then, it will select the next element in order which be the 2nd li in case the first li is clicked and then, we add the class to that element.
Upvotes: 0
Reputation: 121998
There is next()
function
$(this).parent().next().addClass('active');
However this is not what you looking for. This adds a class to li. If you want to add the class to a inside that , you need
$(this).parent().next().find("a").addClass('active');
Upvotes: 0