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

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

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

</body>
</html>


CSS style sheet

<style>
.change
{
font-size:24px;
font-family:Constantia, "Lucida Bright", "DejaVu Serif", Georgia, serif;
color:#585858;
}
</style>


Javascript

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


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.