Remove classes recursively

Asked

Viewed 46 times

1

Test scenario

I have a menu, with sub-items, where each sub-item is a link:

<ul id="MenuTabs" class="nav nav-tabs justify-content-center">
    <li class="nav-item">
        <a id="TabInfo" class="nav-link text-danger active"href="#" onclick="info()"><i class="fas fa-info"></i></a>
    </li>
    <li class="nav-item">
        <a id="Tab1" class="nav-link dropdown-toggle text-dark" data-toggle="dropdown" href="#">Tab 1</a>
        <div class="dropdown-menu">
            <a id="tab1opc1" class="dropdown-item" href="#" onclick="t1o1()">Opção 1 Tab 1</a>
            <a id="tab1opc2" class="dropdown-item" href="#" onclick="t1o2()">Opção 2 Tab 1</a>
        </div>
    </li>
    <li class="nav-item">
        <a id="Tab2" class="nav-link dropdown-toggle text-dark" data-toggle="dropdown" href="#">Tab 2</a>
        <div class="dropdown-menu">
            <a id="tab2opc1" class="dropdown-item" href="#" onclick="t2o1()">Opção 1 Tab 2</a>
            <a id="tab2opc2" class="dropdown-item" href="#" onclick="t2o2()">Opção 2 Tab 2</a>
        </div>
    </li>
    <li class="nav-item dropdown">
        <a id="Tab3" class="nav-link dropdown-toggle text-dark" data-toggle="dropdown" href="#" >Tab 3</a>
        <div class="dropdown-menu">
            <a id="tab3opc1" class="dropdown-item" href="#" onclick="t3o1()">Opção 1 Tab 3</a>
            <a id="tab3opc2" class="dropdown-item" href="#" onclick="t3o2()">Opção 2 Tab 3</a>
        </div>
    </li>
</ul>

Functioning

Each sub-item is a link with an action Jquery, and this action when fired should add the class active in the root tab (so far no problem).

The problem is to know which "previous tab" to remove the class active.


Doubts

  • I wonder, is there a way in Jquery that recursively removes any element that has the class active, in that case.

Something like $('#MenuTabs').removeClass('active'), but to take all elements within the element id="MenuTabs".

  • 1

    It wouldn’t just be $('#MenuTabs .active').removeClass('active')?

  • @Andersoncarloswoss Exactly that teacher! Thank you very much!

1 answer

3


Just you do:

$('.active').removeClass('active');

This will remove the class active of any element than possess it.

If you want to limit the search tree to avoid conflicts with the rest of the page, you can use the CSS selector that defines the element root: root .active, will search only elements with the class .active inside root. Considering the parent element as #MenuTabs, just do:

$('#MenuTabs .active').removeClass('active')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.