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)/))
Mukesh Jakhar - PHP Web Developer
Mukesh Jakhar

This is Mukesh Jakhar. I’m a professional web developer with 3+ years experience. I am always ready for freelance work and i am writing blogs in my free time. I love to learn new technologies and share with others.

I founded PHPKIDA in September 2015. The focus of this website to provide web development tutorials of PHP, WordPress, CodeIgniter, Jquery, MySQL, HMTL, CSS etc and sharing solution to problems which i already solved.

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.