Reputation: 327
How can I add "active" class to the "li" tag not the "a" tag. my code:
var url = document.URL;
$('#example li a[href="'+url+'"]').addClass('active');
Upvotes: 1
Views: 4247
Reputation: 1260
suppose the html is like this:
<div id='example'>
<li>
<a></a>
</li>
</div>
Jquery Code:
var url = document.URL;
$('#example li a').parent('li').attr('class','active');
$('#example li a').attr('href',url);
Upvotes: 0
Reputation: 580
Use the parent
function.
var url = document.URL;
$('#example li a[href="'+url+'"]').parent().addClass('active');
Upvotes: 1
Reputation: 16777
You can use the :has() selector.
var url = document.URL;
$('#example li:has(a[href="'+url+'"])').addClass('active');
You can use the .parent() function (if the anchor is the direct child of the list item).
var url = document.URL;
$('#example li a[href="'+url+'"]').parent().addClass('active');
Another more general option is using the .closest() function (this would work even if the anchor isn't a direct child of the list item).
var url = document.URL;
$('#example li a[href="'+url+'"]').closest("li").addClass('active');
Upvotes: 1