How to create a new element with YUI
I’m starting to dig into YUI and I think this is a good time to clear up some of the early confusions people might have since I’m experiencing them myself now. I typically try to have very little raw javascript in my code, i figure that that only invites the possibility that it won’t work in some browser. Therefore, rather than using ‘document.createElement’, I went searching for a way to create an element with YUI. I ran into a function with seems like it should do the trick, YAHOO.util.Element, which, in their demo code, can be called as a constructor like so:
However, despite that this code seems to imply that a new element will be constructed for you, it is actually just a wrapper for YAHOO.util.Dom.get which simply finds elements already in the DOM for you, like document.getElementById or prototype’s dollar function.
So, contrary to my intuition, YUI does not not provide a wrapper for document.createElement and this is actually what you are supposed to use. However, you’re probably also going to want to be able to treat your element like a YAHOO.util.Element, so you’ll need to assign your element an id and then retrieve it using YUI:
el.id = ‘elem_id’;
yui_el = YAHOO.util.Dom.get(el.id);
Ugly! Now you can use the nice method’s that YUI provides:
I don’t like this design decision at all from YUI. I think that their reasoning is that they don’t want to clutter up the native objects that the browser provides. If that’s the case, then they shouldn’t even have an Element module, it should all just be left in the Dom module. I hope they decide to scrap this before they release it from beta. It simply doesn’t make sense to have two different object types which both refer to elements but which don’t directly inherit from one another.
Cheers!
April 8th, 2009 at 2:12 pm
Thanks for your input sunchameleon!
In my defense, my point was that I thought that calling a constructor should create an element, not retrieve a pointer to an already existing one… They call it a ‘constructor’ for a reason, you even gotta put the word ‘new’ before it!