What is a good approach to add class to a DOM element using JavaScript. And Remove also.
I came across this following codes for adding:
1:
Adapted versions of jQuery's addClass
And jQuery's removeClass
If you look at jQuery source code, this is how they do it. This is adapted from them, but pretty much entirely written by jQuery and is their code. I am not the original author, and am merely showing how one piece can be used instead of the whole library.
jQuery's addClass:
//This code is jQuery's
function AddClassToElement(elem,value){
var rspaces = /\s+/;
var classNames = (value || "").split( rspaces );
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = setClass.replace(/^\s+|\s+$/g,'');//trim
}
jQuery's removeClass:
//This code is jQuery's
function RemoveClassFromElement(elem,value){
var rspaces = /\s+/;
var rclass = /[\n\t]/g
var classNames = (value || "").split( rspaces );
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = className.replace(/^\s+|\s+$/g,'');//trim
}
Here is a working fiddle: http://jsfiddle.net/C5dvL/