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:
Element.prototype.addClassName = function (cls) {
if (!this.hasClassName(cls)) {
this.className = [this.className, cls].join(" ");
}
};
2:
document.querySelector(element).classList.add(cls)
Both of them seem to work for me. What is the difference between them and which is the best?
1. If you are moved by the word prototype, you might want to check MDN Docs - Inheritance and prototype chain.
2. The first code you mentioned is a normal cross-browser way of adding a class to an element.
Instead of being a function declaration, its added as a method to the Element's prototype - so that when you query an Element by its id
(good ol' JavaScript), you can simply call the method on the element itself.
3. The second code you have posted is per the new DOM Specification. W3 Link. It will work only in those browsers that implement the DOM Level 4 Specs. It won't work in old browsers.
That goes the difference.
For the best method, a native method is always the best and fastest.
So for the browsers that support clasList
, the second should be the best. Per my opinion though, till things (drafts) are not finalized you might want to consider a method that works cross-browser and is compatible with both JavaScript (ECMA-3) and supported DOM Spec.
A simple idea should be to change the className
, a property accessible in all new and old browsers, and append your class
as a string to it:
var el = document.getElementById(id);
el.className = el.className + " " + cls;
// mind the space while concatening
Of course you can add validation methods like using regex
for trimming spaces while adding and removing.
By the way, I got the full part of the code you posted as the 1st Example:
Element.prototype.hasClassName = function(name) {
return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className);
};
Element.prototype.addClassName = function(name) {
if (!this.hasClassName(name)) {
this.className = this.className ? [this.className, name].join(' ') : name;
}
};
Element.prototype.removeClassName = function(name) {
if (this.hasClassName(name)) {
var c = this.className;
this.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), "");
}
};
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With