JavaScript
>
Noen biblioteker
>CSS-klasser
Endre class for elementer
Vi kan enten includere (og derved ekesekvere) følgende kode for å tilordne metodene hasClassName, addClassName og removeClassname fra elle elementer:
// from:http://www.html5rocks.com/tutorials/dnd/basics/ 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"), ""); } };
Eller vi kan definere funksjonene slik
function hasClassName(elt,name) { return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(elt.className); }; function addClassName(elt,name) { if (!elt.hasClassName(elt,name)) { elt.className = elt.className ? [elt.className, name].join(' ') : name; } }; function removeClassName(elt,name) { if (elt.hasClassName(elt,name)) { var c = elt.className; elt.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), ""); } };