class-toggle
v1.0.2
Published
Toggle class on HTMLElement
Downloads
9
Readme
class-toggle
Toggle class on HTMLElement
Motivation (YouMightNotNeedJQuery)
JQuery:
$(el).toggleClass(className);
Native (IE 9+):
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = classes.indexOf(className);
if (existingIndex >= 0)
classes.splice(existingIndex, 1);
else
classes.push(className);
el.className = classes.join(' ');
}
class-toggle:
const toggleClass = require('class-toggle');
toggleClass(el, className);
native / polyfill
el.classList.toggle(className);
Protip: use native / polyfill if possible
Install
$ npm install --save class-toggle
Usage
const toggleClass = require('class-toggle');
const div = document.createElement('div')
div.outerHTML
//=> '<div></div>'
toggleClass(div, 'my-class');
div.outerHTML
//=> '<div class="my-class"></div>'
toggleClass(div, 'other-class');
div.outerHTML
//=> '<div class="my-class other-class"></div>'
toggleClass(div, 'my-class');
div.outerHTML
//=> '<div class="other-class"></div>'
License
MIT © Sigurd Fosseng