Remove last class [duplicate]
Asked Answered
E

1

7

When clicking on a div I want to remove the last of it's classes (which is always the third). So, when clicking on the div below I want class3 to be removed, which can have different class names (but always ends with '_hover').

Is there an easy way of doing this?

<div id="container" class="class1 class2 class3">

$('#container').on('click', function() {
    $(this).removeClass(?);
}
Erythrite answered 10/9, 2013 at 21:33 Comment(0)
M
11

One simple way would be to find the last class, then remove it:

var lastClass = $('#container').attr('class').split(' ').pop();
$(this).removeClass(lastClass);

In vanilla JavaScript, you can use:

class.classList.add('className');

// or
 
class.classList.remove('className');
Monocot answered 10/9, 2013 at 21:34 Comment(4)
or better $(this).removeClass(this.className.split(' ').pop());Niagara
I did that to separate the steps.Monocot
Finding last class of an element: #11258846Monocot
I know, note className dont have to use jquery always... :)Niagara

© 2022 - 2024 — McMap. All rights reserved.