I have seen a lot of discussion regarding extending Element
. As far as I can tell, these are the main issues:
- It may conflict with other libraries,
- It adds undocumented features to DOM routines,
- It doesn’t work with legacy IE, and
- It may conflict with future changes.
Given a project which references no other libraries, documents changes, and doesn’t give a damn for historical browsers:
Is there any technical reason not to extend the Element
prototype. Here is an example of how this is useful:
Element.prototype.toggleAttribute=function(attribute,value) {
if(value===undefined) value=true;
if(this.hasAttribute(attribute)) this.removeAttribute(attribute);
else this.addAttribute(attribute,value);
};
I’ve seen too many comments about the evils of extending prototypes without offering a reasonable explanation.
Note 1: The above example is possibly too obvious, as toggleAttribute
is the sort of method which might be added in the future. For discussion, imagine that it’s called manngoToggleAttribute
.
Note 2: I have removed a test for whether the method already exists. Even if such a method already exists, it is more predictable to override it. In any case, I am assuming that the point here is that the method has not yet been defined, let alone implemented. That is the point here.
Note 3: I see that there is now a standard method called toggleAttribute
which doesn’t behave exactly the same. With modification, the above would be a simple polyfill. This doesn’t change the point of the question.