The prototype of some native javascript objects can be extended to include new functions (such as NodeList.prototype.forEach or NodeList.prototype.addEventListener) which I use to allow array and element-like interaction with the NodeList. So far so good, but how should I add an object to the prototype which in turn has it’s own functions (to allow NodeListVar.classList.remove("class")). I have been able to make NodeListVar.classList().remove("class"), by doing the following
NodeList.prototype.classList = function(){
var _this = this;
return {
remove: function(class){
_this.forEach(function(){
this.classList.remove(class);
});
}
}
};
However I would greatly prefer the syntax to be the same as a normal element, thus more like:
NodeList.prototype.classList = {
remove: function(class){
//where *this* would be the nodeList and *not* the DOMWindow
this.forEach(function(){
this.classList.remove(class);
});
}
};
It probably isn’t hard even, but I have searched google endlessly and looked through countless questions already and can’t find anything usefull.
First to read: What’s wrong with extending the DOM.
You can’t set objects on a prototype. All called functions will be executed in context of that static prototype object, not the NodeList itself. The object on the prototype has no reference to the current NodeList.
On normal
Elements, every element has its ownclassListattribute, aDOMTokenListbound the element. You will need to do the same: Give every NodeList its own classLists instance. As you can’t do that in the unavailable constructor, you will have to use a getter, as already demonstrated.I don’t think you should try to allow the same syntax on NodeLists as on Elements, because they are very different. But if you want to get rid of these brackets, you can install a native getter function.