rennacs
rennacs

Reputation: 72

Get parent and add class to all links within

I'm having an issue with adding classes on a nested menu. When I click a link with the class get-view I need to add a class to ALL links within a containing div with the class nav-item including the link I clicked on. I'm completely lost on how to select the containing div and apply a class to all links inside. Any help is mucho appreciated.

My html looks like this

<div class="nav-item">
    <a href="1.html" class="get-view subnav-main"><span>Main Link 1</span></a>
</div>
<div class="nav-item">
    <a href="2.html" class="get-view subnav-main"><span>Main Link 2</span></a>
</div>
<div class="nav-item">
    <div class="subnav-main subnav-more">
        <a href="3.html" class="get-view subnav-main"><span>Main Link 3</span></a>
        <div class="subnav-subnav subnav-closed">
            <a href="3.html" class="get-view">Sublink 1</a><br />
    <a href="4.html" class="get-view">Sublink 2</a><br />
    <a href="5.html" class="get-view">Sublink 3</a><br />
        </div>
    </div>
 </div>

Upvotes: 2

Views: 837

Answers (1)

James Hill
James Hill

Reputation: 61812

This should work:

$(".get-view").click(function() {
    // Remove [YourClass] from any element that might already have it
    $(".YourClass").removeClass("YourClass");

    //Add [YourClass] based on your requirements
    $(this).closest(".nav-item").find("a").addClass("YourClass");
});

Here's a working fiddle.

Upvotes: 3

Related Questions