H Emad
H Emad

Reputation: 327

dynamicly add class active to a menu item with jquery

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

Answers (3)

Jyoti Prakash
Jyoti Prakash

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

Bas Wildeboer
Bas Wildeboer

Reputation: 580

Use the parent function.

var url = document.URL;
$('#example li a[href="'+url+'"]').parent().addClass('active');

Upvotes: 1

Itay
Itay

Reputation: 16777

Alertnative #1 - Select the parent instead of the child

You can use the :has() selector.

var url = document.URL;
$('#example li:has(a[href="'+url+'"])').addClass('active');

Alternative #2 - Use a traversing function to get to the parent

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

Related Questions