user4831663
user4831663

Reputation:

Add class to wrapping element

I'm using the script below to add an active stage according to the current page url.

At the moment, it is adding the "active" class to the <a> tag.
How can I add the class to the wrapping <li> element instead?

$(function() {
  var currenturl = window.location.href;
  $("#navigation ul li a").each(function() {
    if ($(this).attr("href") == currenturl || $(this).attr("href") == '')
      $(this).addClass("active");
  })
});

I think I could use .wrap() somehow, but I'm not sure how.

Upvotes: 0

Views: 185

Answers (2)

indubitablee
indubitablee

Reputation: 8206

$(this).closest('li').addClass('active');

this works if the a tag is somewhere inside the li tag (does not necessarily have to be the direct child)

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try .parent if it is the direct parent you want to add the class or .closest if it is even higher (parent's parent and so on).

$(this).parent().addClass("active");

Assuming it is direct parent from the selector #navigation ul li a

Upvotes: 2

Related Questions