Cheknov
Cheknov

Reputation: 2072

How to change the class of a <li> element after clicking on a tab

I would like to modify the class of certain elements of my sidebar when some user clicks on a tab. In short, change the class of the sidebar elements to current class + " active"

I have implemented a partially working solution as I could after doing some research on my own.

This part of the code is key:

$(".setActive").click(function() {
            $(".sidebar-item:contains('"+$(this).attr("data-target")+"')").parent().parent().addClass(' active');
})

Actually, with that line of code, I change the class to active but there is a problem:

current result

How can I solve this issue?

JS FIDDLE LIVE DEMO

Upvotes: 1

Views: 223

Answers (1)

ProDec
ProDec

Reputation: 5410

Remove all active class added before adding the current one

$(".setActive").click(function() {
    $(".sidebar-element.active").removeClass('active');
    $(".sidebar-item:contains('"+$(this).attr("data-target")+"')").parent().parent().addClass(' active');
})

Upvotes: 1

Related Questions