Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle parent element's class jQuery based on HREF value

As you may tell I am learning jQuery today (amongst other web stuff).

I am trying to neatly change the class of an LI to active when a variable I have matches the contents of the HREF on an A within the LI.

It is structured as follows:

<li><a href="foo.html">Foo</a></li>

When my "page" variable is equal to "foo.html" I want to change the class of the li to active. As follows:

<li class="active"><a href="foo.html">Foo</a></li>

I know there is a moderately simple way of doing it, but the way I am doing it seems to be entirely wrong!

Just as a side note, it is worth bearing in mind (as this is where I have fallen over) that this is a menu, and there are numerous LIs e.g:

<li class="active"><a href="foo.html">Foo</a></li>
<li><a href="bar.html">Bar</a></li>

Many thanks, Kris

like image 832
Kris Douglas Avatar asked Aug 29 '26 09:08

Kris Douglas


2 Answers

This should work:

$('a[href="foo.html"]').closest("li").addClass("active");

To work with your page variable:

$('a[href="' + hrefVariable + '"]').closest("li").addClass("active");

EDIT:

To explain how this works:

  • The first section, $('a[href="foo.html"]') will locate any and all links on the page with the href value of foo.html.
  • The second object, .closest("li") will locate the closest li from the element found in the first section.
  • The third object adds the class to the preceding element, in this case the li.
like image 153
Brian Salta Avatar answered Aug 31 '26 21:08

Brian Salta


Step 1: Getting the correct link element

First you need to locate the correct a tag element, you can do that with the following attribute selector:

var href = "foo.html";
var a = $("[href='" + href + "']");

Step 2: Getting the parent list item element

Then you can find the direct parent using the parent() function:

var li = a.parent();

If it is not a direct parent, you can use the closest() function which will allow you to find the first ancestor that matches the supplied selector. For example:

var li = a.closest("li");

Step 3: Changing the class

Finally, you can add a class to any given element using the addClass() function:

li.addClass("active");

if you need to remove the class at any point, or remove an existing class, you can use the removeClass() function:

li.removeClass("active");

NOTE: If you want to 'reset' all active list elements, you can easily do the following:

$("li.active").removeClass("active");

The end result

Here is a working example in action

like image 23
musefan Avatar answered Aug 31 '26 22:08

musefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!