JSFiddle - React, Tailwind, and code Playground
HTML
<button id="toggle" onclick="toggle(this.id)">toggle</button>
<button id="add" onclick="toggle(this.id)">add</button>
<button id="remove" onclick="toggle(this.id)">remove</button>
<p id="thetext">some text</p>
JavaScript
// If newState is provided add/remove the class accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
function toggle(id) {
var elem = document.getElementById('thetext');
if (id=='toggle') toggleClass(elem, 'red');
if (id=='add') toggleClass(elem, 'red', true);
if (id=='remove') toggleClass(elem, 'red', false);
}