Angel Politis Angel Politis - 6 months ago 24
Javascript Question

How do I supplant jQuery's toggleClass method with pure JavaScript?

How can I turn this piece of jQuery code into JavaScript?

$('#element').click(function(){
$(this).toggleClass('class1 class2')
});


I have already tried the following pieces of code, but to no avail.

First one is:

var element = document.getElementById('element');
element.onmousedown = function() {
var classNum = 0; // Supposing I know that the first time there will be that class
if (classNum === 0) {
this.classList.remove("class1");
this.classList.add("class2");
classNum = 1;
}
else if (classNum === 1) {
this.classList.remove("class2");
this.classList.add("class1");
classNum = 0;
}
}


Second one is:

var element = document.getElementById('element');
element.onmousedown = function() {
var classNum = 0; // Supposing I know that the first time there will be that class
if (classNum === 0) {
this.className -= "class1";
this.classList += "class2";
classNum = 1;
}
else if (classNum === 1) {
this.classList -= "class2";
this.classList += "class1";
classNum = 0;
}
}


Any answer that doesn't suggest that I stick with jQuery will be greatly appreciated.

[EDIT]

I've tried all of your solutions, but haven't been able to get it right. I believe it's because I didn't state clearly that the element has multiple classes like so:

class="class1 class3 class4"


And what I want is basically to replace class1 with class2 and toggle between them.

Answer

UPDATED MY ANSWER TO SUPPORT MULTIPLE CLASSES PER ELEMENT

https://jsfiddle.net/pwyncL8r/2/ This will now allow the element to already have n classes and still swap only one, retaining the other classes.

HTML

<div id="div1" style="width: 100px; height: 100px;" class="backBlack left100"</div>
<input type="button" id="swapButton" value="Css Swap" />

CSS

.backBlack {
    background-color: black;
}

.backRed {
    background-color: red;
}

.left100 {
    margin-left: 100px;
}

JS

swapButton.onclick = function() {
    var curClassIsBlack = (' ' + document.getElementById("div1").className + ' ').indexOf(' backBlack ') > -1
    if (curClassIsBlack) {
        document.getElementById("div1").className =
        document.getElementById("div1").className.replace(/(?:^|\s)backBlack(?!\S)/g, '')
        document.getElementById("div1").className += " backRed";
    } else {
        document.getElementById("div1").className =
        document.getElementById("div1").className.replace(/(?:^|\s)backRed(?!\S)/g,'')
        document.getElementById("div1").className += " backBlack";
    }
}