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