/**
* If it exists, delete it. If it does not exist, add it
* @param {HTMLElement} element
* @param {string} className
*/
function toggleClass (element, className) {
if (!element || !className) {
return
}
if (hasClass(element, className)) {
removeClass(element, className)
} else {
addClass(element, className)
}
}
/**
* Check if an element has a class
* @param {HTMLElement} elm
* @param {string} cls
* @returns {boolean}
*/
function hasClass (element, className) {
className = className || ''
if (className.replace(/\s/g, '').length === 0) return false
return new RegExp(' ' + className + ' ').test(' ' + element.className + ' ')
}
/**
* Add class to element
* @param {HTMLElement} elm
* @param {string} cls
*/
function addClass (element, className) {
if (!hasClass(element, className)) {
element.className += ' ' + className
}
}
/**
* Remove class from element
* @param {HTMLElement} elm
* @param {string} cls
*/
function removeClass (element, className) {
if (hasClass(element, className)) {
let newClass = ' ' + element.className.replace(/[\t\r\n]/g, '') + ' '
while (newClass.indexOf(' ' + className + ' ') >= 0) {
newClass = newClass.replace(' ' + className + ' ', ' ')
}
element.className = newClass.replace(/^\s+|\s+$/g, '')
}
}