Element.extend an Element in Prototype
Here's a quick way to add all the Element methods to a DOM element using Prototype 1.5 (I believe the RC is right around the corner if not already here).
var div = document.createElement('div');
Element.extend(div);
That's it. Then you can do things like div.show()
or div.hide()
. Well, you still need to append the DIV to the document but you get the idea.
Conversation
I'm hesitant to switch over to using Protoype since writing my own code library has enhanced my JS knowledge greatly, but I don't know if I can spend much more time on it! All the same, I have similar functionality by creating methods for HTMLElement.prototype (and then copying the properties to the DOM nodes for IE).
I also made newElement() which essentially passes a new element through the same process at run-time.
Therefore every element, regardless of when it was created, has .setClass(), .ajax() methods etc.
I guess I just prefer $(el).doSomething() !
Ah. Having just looked at the script.aculo.us wiki I realise this is pretty much what 1.5 will do anyway. Time to switch.
If you use Dan Webb's awesome DOMBuilder script, you can modify it to return "extended" versions of elements automatically. If you don't use DOMBuilder, you should � you'll never use createElement() again.
I'm not sure I follow, can't you do that anyway without explicitly making that Extend call?
Like:
div = document.createElement('div')
div.update('<p>I like prototype</p>')
The only place I see this not working is in naughty browsers, like IE, but this seems to fix it:
div = document.createElement('div')
div = $(div)
div.update('<p>I like prototype</p>')
Maybe I'm not reading this correctly?
My html wasn't encoded, but you get the idea.
Justin:
Element.extend
is technically only needed for IE and any other browser that won't let you modifyHTMLElement.prototype
. This is why your first example works in Firefox.For the sake of IE compliance you have to explicitly "extend" DOM nodes, using either
Element.extend
or$
(which extends anything it returns). I prefer the latter because it's shorter.Note that
getElementsByClassName
and$$/getElementsBySelector
will also extend any nodes they return.Yes I'm quite familiar with IE's reluctance to do this, but didn't really understand the *why*.
If you asked me 6 months ago, I would have told you to use calls to $() sparingly, but I'm now finding myself calling it on all the time for the very reason you stated above.
I figured $() and Element.extend() were mostly the same, but still, I've never even heard of extend() until now.
$() and Element.extend are very similar in that $() will automatically extend the element. But, it prevents a small overhead (the dollar function doesn't have to enter a loop for one element and push that one element onto an array to be returned back) and makes the code easier to understand.
I usually use