Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)
Can anyone help me how I can able to add or remove classes in JavaScript without using jQuery? Any fast and secure way to do that?

1 Answer

0 votes
by (26.7k points)

You can use the below code for achieving it. Also, for the 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, ' ');

    }

}

I hope this will help.

Want to know more about Java? Prefer this tutorial on Learn Java.

Want to become a Java Expert? Join Java Course now!!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 7, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Aug 10, 2019 in Web Technology by Sammy (47.6k points)

Browse Categories

...