user2190590
user2190590

Reputation: 3

Remove previously added class by jQuery

I have a follow up question to this: Add and remove a class on click using jQuery?

I'm able to add a class to a specific li element using this snipped by Jamie Taylor:

$('.team').on('click', 'li', function() {
    $('.team li#member').removeClass('more');
    $(this).addClass('more');
});

I'd like to remove the Class .more again, by clicking a toggle element inside the li-item.

My jQuery Snippet which doesn't work:

$('.toggle-x').click(function () {
    $('.team li#member').removeClass('more');
})

Thanks for the help!

Upvotes: 0

Views: 490

Answers (3)

mpcabd
mpcabd

Reputation: 1807

Your problem is because when you click on an element X inside the <li /> the element fires the click event, and if you don't use event.stopPropagation() the <li /> will also fire the click event and the class will be added again.

Try this:

$('.toggle-x').click(function (e) {
    $('.team li#member').removeClass('more');
    e.stopPropagation();
})

It should work if that's your problem.

Upvotes: 0

Hamix
Hamix

Reputation: 1335

try this

    $(".innerLiContent").click(function(){
       $(this).parentsUntil( "li" ).removeClass('more');
    });

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

In your code, it will remove the class form only one element with id member. If you want to remove the class from all the li elements, use like this,

$('.team li.more').removeClass('more');

Upvotes: 1

Related Questions