Extending DOM Elements has many negative side effects and I would say is even considered harmful. In that Ajaxian article, you can find a link to Kangax’s post that explains what is wrong with extending the DOM.
So here’s some ideas for Element wrappers that I’ve toyed around with myself. I’ll call the Element wrapper class
$ type function
You can choose any name, but in Prototype and MooTools, the
$ function takes an ID or element and returns an extended Element.
$is a shortcut for
$accepts string IDs, html strings, DOM Elements and
$should ensure that only one wrapper is created per Element. You can store a reference to the wrapper in an expando property or in a hash of
id => WrappedElpairs.
This is where the magic happens.
WrappedElshould provide functions to manipulate every native property or function. Some examples:
WrappedEl#getAttribute()to provide a cross-browser method that mirrors
WrappedEl#setProperty()to set properties directly.
- Should provide a way to add methods. Would be nice if it provides a way to add methods for a certain tag. In that case it is probably best to use subclasses; e.g.
WrappedElis a parent of
WrappedElTextarea. It even makes sense to add new methods by default to some tags; e.g. add a
WrappedElTextarea#value()to get and set the
valueproperty of a textarea.
- Should feel the same as DOM Element extension. If current scripts avoid using properties such as
WrappedElcould even be compatible with an API that extends DOM Elements.
- It is nice if the
WrappedElclass provides generics. In other words the ability to call all the instance methods statically by passing the element as the first argument.
WrappedEl is ready, you are not many lines away from adding jQuery-like API. So you might as well code it!
- Create a collection class–called, say,
- Define a method for every
- Chainable methods like setters should return the
- Methods that return an HTML NodeList should return a concatenated collection of
WrappedElobjects in an
Array–or even better–in a
- Some methods such as
getAttributeshould return the result for the first
WrappedElin the collection.
- The method to add methods to
WrappedElmay even be smart enough to automatically add methods to
I’d love to hear your ideas or suggestions in the comment section!