Angel Politis Angel Politis - 4 months ago 12
Javascript Question

Custom JavaScript addClass method

Currently in JavaScript, in order to add a class to an element I use:

var element = document.getElementById("element");

var classes;
if (element.className.split(" ").indexOf("class") < 0) {
classes = element.className.split(" ");
classes.push("class");
element.className = classes.join(" ");
}


If I wanted to make that code a method like jQuery's
addClass()
like below:

addClass: function(string) {
var classes;
if (element.className.split(" ").indexOf("class") < 0) {
classes = element.className.split(" ");
classes.push("class");
element.className = classes.join(" ");
}
}


In which object's prototype should I add this method to work like this:

document.getElementById("element").onclick = function() {
this.addClass("class");
}

Answer

I believe you would add it to the Element object prototype

Element.prototype.addClass = function(className){
    // something
}
Comments