Search code examples
javascriptjqueryhtmlparent-childparent

How do I select a parent element with jQuery


I have a menu in which I'd like to set both the list item and link to the "active" class I've set up when on the active url.

Here is my HTML:

<ul id="featured-projects">
     <li><a href="featured-project.php?id=1" title="Click to view 138 50th Street">138 50TH STREET</a></li>
     <li><a href="featured-project.php?id=2" title="Click to view 147 East 86th Street">147 EAST 86TH STREET</a></li>
     <li><a href="featured-project.php?id=3" title="Click to view 520 Fifth Avenue">520 FIFTH AVENUE</a></li>
</ul>

And jQuery:

$("#featured-projects li a").each(function() {   
    if(this.href == window.location.href) {
        $(this).addClass("active");
        $("li").addClass("active");
    }
});

How would I set the list item to active as well without setting every list item to active?


Solution

  • What you are looking for is parent(). Well named as it is, it always selects the parent node(s) of the matched element(s). Full description here: https://api.jquery.com/parent/

    $("#featured-projects li a").each(function() {   
        if(this.href == window.location.href) {
            $(this).addClass("active");
            $(this).parent().addClass("active"); //Select the parent element of the link in question and add the class
        }
    });