I'd like to add two methods in the Array.prototype which will work a bit like addClass / removeClass of jQuery. This is what I've written:
Array.prototype.addClass = function (className) {
this.forEach((element) => {
element.classList.add(className);
});
};
Array.prototype.removeClass = function (className) {
this.forEach((element) => {
element.classList.remove(className);
});
};
I was told it's generally a bad idea to add methods to built in JS prototypes, so I was wondering what the best alternatives would be to avoid potential gotchas.
My ideas :
- check if the method already exists
- just make a normal function that takes 2 arguments, the array and the classname
- create my new custom object which will have the DOM manipulation methods I build
I am also looking at https://github.com/franciscop/umbrella/blob/master/src/plugins/addclass/addclass.js and how it's implemented.