Toggle Element Class in 2 lines of JavaScript
Uses HTML5's implementation of the classList property. HTML5 assigns the classList property to each element of the document. Implemented in all major browser version except IE. A shim can be found at: https://github.com/eligrey/classList.js
by Nevear
HTML
<h3>Click Box to Toggle</h3>
<div id="statusbox" onClick="toggleStatus(this)">
<p>
If box is red then this is an error message
</p>
<p>
If box is green then the status is ok
</p>
</div>
CSS
.ok {
color: #F0F0F0;
background: #FF5151;
}
.error {
color: #787878;
background: #C9FF93;
}
.ok p, .error p {
padding: .5em;
}
#statusbox {
width: 150px; /*Setting width for purpose of demo*/
}
JavaScript
function toggleStatus(e) {
e.classList.toggle("error");
}