Use CSS Class

Course- Javascript >

Using JavaScript to edit the properties of the style object, as in the previous exercise, works well—but it does carry with it the danger of reducing this separation of style and content. If your JavaScript code routinely changes elements’ style declarations, the responsibility for styling your pages is no longer lodged firmly in CSS. If you later decide to change the styles your JavaScript applies, you’ll have to go back and edit all of your JavaScript functions.

Thankfully, we have a mechanism by which JavaScript can restyle pages without overwriting individual style declarations. By using the className property of the element, we can switch the value of the class attribute and with it the associated style declarations for the element. Take a look below code.

<!DOCTYPE html>
<html>
<head>
<title>Switching classes with JavaScript</title>
<style>
.classA {
width: 180px;
border: 3px solid black;
background-color: white;
color: red;
font: normal 24px arial, helvetica, sans-serif;
padding: 20px;
}
.classB {
width: 180px;
border: 3px dotted white;
background-color: black;
color: yellow;
font: italic bold 24px "Times New Roman", serif;
padding: 20px;
}
</style>
<script>
function toggleClass() {
var myElement = document.getElementById("id1");
if(myElement.className == "classA") {
myElement.className = "classB";
} else {
myElement.className = "classA";
}
}
window.onload = function() {
document.getElementById("btn1").onclick = toggleClass;
}
</script>
</head>
<body>
<div id="id1" class="classA"> An element with a touch of class.</div>
<input type="button" id="btn1" value="Toggle" />
</body>
</html>                 
                 

The <style> element in the page <head> lists style declarations for two classes, classA and classB. The JavaScript function toggleClass() uses similar logic to the earlier function toggle() of above code, except that toggleClass() does not work with the element’s style object. Instead, toggleClass() gets the class name associated with the <div> element and switches its value between classA and classB.

Switching classes in JavaScript As an alternative to using className, you could try setting the class attribute for an element to the value classA by using element.setAttribute("class", "classA"); Unfortunately, various versions of Internet Explorer have trouble when trying to set the class attribute, but work fine with className. The statement element.className = "classA";seems to work in all browsers.