Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  188] [ 7]  / answers: 1 / hits: 21725  / 12 Years ago, mon, december 31, 2012, 12:00:00

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?


More From » javascript

 Answers
6

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), );
}
};

[#81149] Saturday, December 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisc

Total Points: 533
Total Questions: 82
Total Answers: 90

Location: Bangladesh
Member since Thu, Aug 5, 2021
3 Years ago
;