How To Add or Remove a Class Using Raw JavaScript and jQuery

If you want to dynamically set or remove a CSS class name for a HTML element, then you need to do some javaScript works. We can do this by using raw javaScript. jQuery is also a popular javaScript library. You can use jQuery also. Here I am showing you the both way to add/remove class.

Using Raw JavaScript:

Removing a class

 var id='myElementId';
 var myClassName=" className"; //must keep a space before class name
 var d;
 d=document.getElementById(id);
 d.className=d.className.replace(myClassName,"");

Adding a class


var id='myElementId';
var myClassName=" className"; //must keep a space before class name
var d;
d=document.getElementById(id);
d.className=d.className.replace(myClassName,""); // first remove the class name if that already exists
d.className = d.className + myClassName; // adding new class name

Using jQuery:

Adding a class

jQuery("#myElementId").addClass('className');

Removing a class

jQuery("#myElementId").removeClass('className');

Remove one class and add another new class at once

jQuery("#myElementId").removeClass('className').addClass('newClass');

Remove one more class at once

jQuery("#myElementId").removeClass('className1 className2');


If you think this codes are helpful to you then don’t forget to share this to others.


These codes may be the answer of following queries

  • Javascript function to Add a Class
  • Using Javascript to add CSS class
  • Javascript function to remove a class
  • Remove a CSs class by javaScript
  • JS code snippet to add/remove class
  • jQuery function to add/remove any CSS class
  • jQuery addClass function
  • JQuery removeClass function
  • Dinamically change style of an HTML element
  • Change HTML Class attributes
  • javascript add class to element
  • javascript remove class
  • Add/Remove Class with jquery function
  • Adding a class to a .click function
  • Add Remove CSS Class Using Fresh JavaScript Without jQuery

3 Comments


  1. How about:

    document.getElementById(‘id’).classList.add(‘class’);
    document.getElementById(‘id’).classList.remove(‘class’);

    Reply

  2. I would not rely on plain replace() for vanilla JS; instead, I would use RegExp replace() like this:


    var re = new RegExp(' *' + myClassName + ' *');
    d.className = d.className.replace(re, '');

    This way you won’t have to worry about requiring the developer to keep a space before the class name and taking that into account when doing className string comparisons.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *