Reputation: 541
Why is this not adding a class to :
<ul class="sub-menu" style="display: none;">
HTML:
<ul class="sub-menu" style="display: none;">
<li id="menu-item-18" class="current-menu-item page_item current_page_item">
<a href="#">Sitename</a>
</li>
</ul>
JQuery:
if ($('.sub-menu li').hasClass('current-menu-item')) {
$(this).parent().addClass('active');
}
Same result with:
if ($('li').hasClass('current-menu-item')) {
$(this).parent().addClass('active');
}
Upvotes: 0
Views: 463
Reputation: 700192
Because this
doesn't refer to the element that you located in the if
statement.
You would loop through the elements and check each one:
$('.sub-menu li').each(function(i, el){
if ($(el).hasClass('current-menu-item')) {
$(el).parent().addClass('active');
}
});
However, in this case you can just select the matching elements, get each parent element and add the class to all of them:
$('.sub-menu li.current-menu-item').parent().addClass('active');
Upvotes: 1