After being frustrated of not getting consistent and accurate result via standard DOM methods especially
html_element.setAttribute('key', 'value');, I came across some YUI library components that provides abstractions to various DOM methods. Some interesting DOM-related tools covered in this post are
YAHOO.util.Element is basically a singleton instance that provides various DOM methods. Following are some of the methods that one may find useful. For more information, please refer to the API documentation.
Finding an Element by Id
To find an element by its Id, instead of document.getElementById, another way through YUI would be through YAHOO.util.Dom.get.
var element = YAHOO.util.Dom.get('some_element');
Finding Element(s) by Class Name
To find elements by class name,
var elements = YAHOO.util.Dom.getElementsByClassName('some_class');
Before I discover how powerful is jQuery, I have relied on
YAHOO.util.Element a lot in various tasks. Basically,
YAHOO.util.Element wraps a HTMLElement and provide some methods to simplify the code used in certain DOM operations such as getting and setting attributes, manipulating element position etc. Detailed API documentation is here.
Creating a New Element
To create a new element, one typically pass in the result from
document.createElement into the constructor as follows. For example, to create a new link element.
// create a new element
var element = new YAHOO.util.Element(document.createElement('a'));
// set the href
// insert caption
'Click me to the search engine.'
Uses an existing Element
To wrap YUI Element component methods to an existing HTMLElement, pass in the element OR the element Id into the constructor.
var by_element = new YAHOO.util.Element(
var by_id = new YAHOO.util.Element('some_id');
Getting the original HTMLElement
Sooner or later one would find out that it is impossible to call some DOM methods through the
YAHOO.util.Element instance, for instance the
setAttribute method. Besides that, as of 2.6.0, the appendChild method also doesn’t seem to accept instance from
YAHOO.util.Element. Therefore to get the wrapped element,
var some_container = new YAHOO.util.Element(container_element);
var the_yui_element = new YAHOO.util.Element(original_element);
// this will result in an error
// but this won't
Hopefully instances of
YAHOO.util.Element are also accepted by all methods requiring HTML element in future releases.
DOM Collection via CSS3 Selector
Those who are from jQuery may be interested in knowing that YUI also provides similar functionality via
YAHOO.util.Selector. For those who are interested, the API documentation is here. As an example,
var elements = YAHOO.util.Selector.query('body p');
YAHOO.util.Event, which is my favorite component next time.
Thank you for this information.