Objectives and outcomes

In this tutorial we going to learn about how to change the class of a document element using only javascript and no jquery. While this task is very easy to perform using jquery but if we don't want to attach jquery script to our document than the same goal can also be achieved using simple javascript as shown below:

Change class without Jquery


HTML code

<meta charset="utf-8">
<title>Change class</title>

<div id="example">
Change class without Jquery
<button onClick="attach_class();">Add class</button> &nbsp;
<button onClick="remove_class();">Remove class</button>


CSS style sheet

font-family:Constantia, "Lucida Bright", "DejaVu Serif", Georgia, serif;


function attach_class()
document.getElementById('example').className = 'change';
function remove_class()
document.getElementById('example').className = document.getElementById('example').className.replace
( /(?:^|\s)change(?!\S)/g , '' );

On clicking add class button class named 'change' is attached to div with id="example" and on clicking remove class button the same class is removed. The regular expression in this case states that ignore the names of other classes only the class named 'change' is to be replaced by a white-space.