Skip to content
Advertisement

How to add and remove classes in Javascript without jQuery

I’m looking for a fast and secure way to add and remove classes from an html element without jQuery.
It also should be working in early IE (IE8 and up).

Advertisement

Answer

The following 3 functions work in browsers which don’t support classList:

function hasClass(el, className)
{
    if (el.classList)
        return el.classList.contains(className);
    return !!el.className.match(new RegExp('(\s|^)' + className + '(\s|$)'));
}

function addClass(el, className)
{
    if (el.classList)
        el.classList.add(className)
    else if (!hasClass(el, className))
        el.className += " " + className;
}

function removeClass(el, className)
{
    if (el.classList)
        el.classList.remove(className)
    else if (hasClass(el, className))
    {
        var reg = new RegExp('(\s|^)' + className + '(\s|$)');
        el.className = el.className.replace(reg, ' ');
    }
}

https://jaketrent.com/post/addremove-classes-raw-javascript/

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement