how to add css class using javascript

If you are trying to add css class using JavaScript this is tutorial only for you, Here i am explaining how to add css class using JavaScript.
The standard JavaScript way to first select an element is using document.getElementById(“Id”), just follow below example use:

To change all classes for an element:
To replace all existing classes with one or more new classes, set the className attribute. (You can use a space-delimited list to apply multiple classes.)

    document.getElementById("MyIdName").className = "MyNewClassName";

Add an additional class to an element:
To add a class to an element, without removing/affecting existing values, append a space and the new className:

    document.getElementById("MyIdName").className += " MyClassName";

To check if a class is already applied to an element:
The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

    if (document.getElementById("MyIdName").className.match(/(?:^|\s)MyClassName(?!\S)/))
About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.