I'm trying to add simple functions to the JavaScript DOM, e.g. an addClass
function, I implemented this first with the following code:
Element.prototype.addClass = function(className) {
this.className += ' ' + className;
};
However after much reading (http://perfectionkills.com/whats-wrong-with-extending-the-dom/ was good) it seems this is a terrible way to extend the DOM for a number of reasons.
The above article states:
One of the most common alternatives to this whole mess of DOM extension is object wrappers
Which is fine, apparently the general consensus is to use Object wrappers if you want to extend the DOM. The problem is I can't find any good examples anywhere on how you actually use object wrappers to extend the DOM ...
Can anybody give me an example of how to do so? Maybe using the above code?
Object wrappers are more expensive than extensions because you need to create a new object, but they are safer.
A simple implementation that wraps only a single element could look like this:
(function() {
window.wrap = function(el) {
return new Wrapper(el);
};
function Wrapper(el) {
this.element = el;
}
Wrapper.prototype.addClass = function(cls) {
if (this.element)
this.element.className += " " + cls;
}
Wrapper.prototype.swap = function(el) {
this.element = el;
}
})();
Then you could make a new wrapper, and to be more efficient, you could reuse it with various elements.
var wrp = wrap(document.body);
wrp.addClass("foo");
wrp.swap(document.body.firstElementChild);
wrp.addClass("bar");
Another feature you could implement would be to add return this;
to all the wrapper methods. That way you could chain your function calls if you like.
var wrp = wrap(document.body);
wrp.addClass("foo")
.swap(document.body.firstElementChild)
.addClass("bar");
You could also implement your wrapper to hold multiple elements at numeric indices like an Array, or better, simply hold an Array of elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With