Toggle parent element's class jQuery based on HREF value
class, href, html-lists, jquery, toggle
Solution
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.
Problem
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