YUI recommends YUI3.

YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.

This documentation is no longer maintained.

YUI 2: Element Utility

YUI 2: Element Utility

Satyam's YUIBlog article on Building Widgets with YUI is a great place to start as you learn about the role of the Element Utility in YUI..The Element class provides a wrapper for HTMLElements in the DOM and makes simpler common tasks such as adding listeners, manipulating the DOM, and setting and getting attributes. The Element Utility provides a wrapper so that these actions can be performed directly on an Element instance.

While this User's Guide and the API docs are helpful in understanding the role of the Element Utility within YUI, the most extensive guide to creating Element-based components of your own is found in Satyam's article "Building Your Own Widget Library with YUI". Satyam explores the full pattern of using Element, and through it EventProvider and AttributeProvider, to create YUI-style component interfaces. If you're interested in Element because you're interested in building YUI-based widgets or extending YUI-based widgets built on this pattern, Satyam's article is a must-read.

Getting Started

To use the Element Utility, include the following source files in your web page with the <script> tag:

  1. <!-- Dependencies -->
  2. <script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
  3.  
  4. <!-- Source file -->
  5. <script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script>
  6.  
<!-- Dependencies -->
<script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
 
<!-- Source file -->
<script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script>
 

YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.

Note: If you wish to include this component via the YUI Loader, its module name is element. (Click here for the full list of module names for YUI Loader.)

Where these files come from: The files included using the text above will be served from Yahoo! servers. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.

Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.

Basic Element

To create a new Element instance, pass either the ID of the element or a reference to the HTMLElement to the Element constructor:

  1. var el = new YAHOO.util.Element('foo');
  2.  
var el = new YAHOO.util.Element('foo');
 

In this example, a new instance of YAHOO.util.Element is created for an element whose id is foo. If foo is not yet available in the document, event listeners may still be added, and attibutes may be set; the Element Utility will automatically defer those actions until the element becomes available. Be aware, however, that true manipulation of the element's DOM may not be performed until the contentReady event has fired. (Note: onContentReady is a YUI construct supported by the YUI Event Utility.)

Let's look at these steps in a code example:

  1. //create a new instance of Element wrapping
  2. //'foo', which isn' yet on the page
  3. var el = new YAHOO.util.Element('foo');
  4.  
  5. //add a click event handler to 'foo'
  6. el.on('click', function(e) { alert('clicked'); });
  7.  
  8. //when 'foo' is loaded on the page, we'll fire
  9. //an anonymous function that alerts the
  10. //number of list items in 'foo', which is a
  11. //<ul> element:
  12. el.on('contentReady', function() {
  13. var items = el.getElementsByTagName('li');
  14. alert(items.length);
  15. });
  16.  
//create a new instance of Element wrapping 
//'foo', which isn' yet on the page
var el = new YAHOO.util.Element('foo');
 
//add a click event handler to 'foo'
el.on('click', function(e) { alert('clicked'); });
 
//when 'foo' is loaded on the page, we'll fire
//an anonymous function that alerts the
//number of list items in 'foo', which is a 
//<ul> element:
el.on('contentReady', function() {
    var items = el.getElementsByTagName('li');
    alert(items.length);
});
 
  1. <!--markup for foo-->
  2. <div id="foo">
  3. <ul>
  4. <li>lorem</li>
  5. <li>ipsum</li>
  6. <li>dolor</li>
  7. <li>sit</li>
  8. </ul>
  9. </div>
  10.  
<!--markup for foo-->
<div id="foo">
    <ul>
        <li>lorem</li>
        <li>ipsum</li>
        <li>dolor</li>
        <li>sit</li>
    </ul>
</div>
 

Using Element

This section describes several common uses of Element. It contains these subsections:

Using Element to Attach Event Listeners

All Element events are applied using the addListener method (alised as on and can be removed with removeListener.

  1. //create an Element instance wrapping 'foo':
  2. var el = new YAHOO.util.Element('foo');
  3.  
  4. //create an event listener:
  5. var handleClick = function(e) {
  6. alert(el.get('id') + ' clicked');
  7. //remove this listener, so that
  8. //it only fires on the firs click:
  9. el.removeListener(handleClick);
  10. };
  11.  
  12. //assign an event listener using 'on';
  13. //el.addListener and el.on are identical here:
  14. el.on('click', handleClick);
  15.  
//create an Element instance wrapping 'foo':
var el = new YAHOO.util.Element('foo');
 
//create an event listener:
var handleClick = function(e) {
    alert(el.get('id') + ' clicked');
	//remove this listener, so that
	//it only fires on the firs click:
    el.removeListener(handleClick);
};
 
//assign an event listener using 'on';
//el.addListener and el.on are identical here:
el.on('click', handleClick);
 

The above example invokes the handleClick function when the element whose id attribute is foo is clicked. The handler then removes the listener, so subsequent clicks will not fire the event.

Using the delegate Method

Event delegation is a technique whereby you use a single event handler on a parent element to listen for interactions that affect the parent's descendant elements; because events on the descendant elements will bubble up to the parent, this can be a reliable and extremely efficient mitigation strategy for reducing the number of resource-consuming event handlers you have on any given page. (You can read more about Event Delegation in this YUIBlog article.)

The Element Utility makes using event delegation easy by providing a delegate method that enables the use of CSS selector syntax to define the descendants of the delegation container for which the event listener should be called.

Element's delegation functionality is packaged separately in an element-delegate module, which itself requires the event-delegate module and Selector Utility. Therefore, to use Element's delegation functionality include the dependancies as follows:

  1. <script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
  2.  
  3. <!-- Element source file -->
  4. <script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script>
  5.  
  6. <!-- Selector source file -->
  7. <script src="http://yui.yahooapis.com/2.9.0/build/selector/selector-min.js"></script>
  8.  
  9. <!-- Event Delegation Module source file -->
  10. <script src="http://yui.yahooapis.com/2.9.0/build/event-delegate/event-delegate-min.js"></script>
  11.  
  12. <!-- Element Event Delegation Module source file -->
  13. <script src="http://yui.yahooapis.com/2.9.0/build/element-delegate/element-delegate-min.js"></script>
  14.  
<script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
 
<!-- Element source file -->
<script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script>
 
<!-- Selector source file -->
<script src="http://yui.yahooapis.com/2.9.0/build/selector/selector-min.js"></script>
 
<!-- Event Delegation Module source file -->
<script src="http://yui.yahooapis.com/2.9.0/build/event-delegate/event-delegate-min.js"></script>
 
<!-- Element Event Delegation Module source file -->
<script src="http://yui.yahooapis.com/2.9.0/build/element-delegate/element-delegate-min.js"></script>
 

Creating A Delegated Event Listener

Consider the following HTML.

  1. <div id="container">
  2. <ul>
  3. <li id="item-1"><em>Item Type One</em></li>
  4. <li id="item-2"><em>Item Type Two</em></li>
  5. <li id="item-3"><em>Item Type Three</em></li>
  6. </ul>
  7. </div>
  8.  
<div id="container">
	<ul>
		<li id="item-1"><em>Item Type One</em></li>
		<li id="item-2"><em>Item Type Two</em></li>
		<li id="item-3"><em>Item Type Three</em></li>
	</ul>
</div>
 

To use the delegate method, pass the type of event you want to delegate, the event listener, and a CSS selector that defines the descendant elements that must match the target of the event in order for the listener to be called.

The following example will bind a single click event listener to the container (<div id="container">) but that listener will only be called if the target of the event is an <li>.

  1. var container = new YAHOO.util.Element('container');
  2.  
  3. container.delegate("click", function(e, matchedEl) {
  4.  
  5. // The list item that matched the provided selector is the default scope
  6. YAHOO.log("Default scope: " + this.id);
  7.  
  8. // The list item that matched the provided selector is also passed
  9. // as the second argument in case the scope of the listener
  10. // is adjusted
  11. YAHOO.log("Clicked list item: " + matchedEl.id);
  12.  
  13. // The actual click target, which could be the matched item or a
  14. // descendant of it.
  15. YAHOO.log("Event target: " + YAHOO.util.Event.getTarget(e));
  16.  
  17. // The delegation container is passed as a third argument
  18. YAHOO.log("Delegation container: " + container.id);
  19.  
  20. }, "li");
  21.  
var container = new YAHOO.util.Element('container');
 
container.delegate("click", function(e, matchedEl) {
 
	//	The list item that matched the provided selector is the default scope
	YAHOO.log("Default scope: " + this.id);
 
	//	The list item that matched the provided selector is also passed 
	//	as the second argument in case the scope of the listener 
	//	is adjusted
	YAHOO.log("Clicked list item: " + matchedEl.id);
 
    //	The actual click target, which could be the matched item or a
    //	descendant of it.
	YAHOO.log("Event target: " + YAHOO.util.Event.getTarget(e));
 
	//	The delegation container is passed as a third argument
	YAHOO.log("Delegation container: " + container.id);
 
}, "li");
 

Attributes and Properties

All of the attributes and properties of the HTMLElement can be accessed via the set and get methods of Element. Additionally, the actual HTMLElement bound to the Element instance can be retrieved via get('element').

  1. //create an Element instance wrapping 'foo':
  2. var el = new YAHOO.util.Element('foo');
  3. //we can now use the instane's get method to retrieve
  4. //attributes and properties of 'foo':
  5. alert(el.get('id') + ' has ' + el.get('childNodes').length + ' children');
  6.  
//create an Element instance wrapping 'foo':
var el = new YAHOO.util.Element('foo');
//we can now use the instane's get method to retrieve
//attributes and properties of 'foo':
alert(el.get('id') + ' has ' + el.get('childNodes').length + ' children');
 

The above example alerts the element's id attribute and the number of childNodes owned by that element.

If the element is not yet available, you will need to defer accessing the HTMLElement until the contentReady event fires. You can write deferral code as follows:

  1. //create an Element instance wrapping 'foo';
  2. //'foo' is not yet on the page.
  3. var el = new YAHOO.util.Element('foo');
  4.  
  5. //When 'foo' becomes available, we want to alert
  6. //its id and show the number childNodes; we tell the
  7. //Element instance to do this when the contentReady
  8. //event fires:
  9. el.on('contentReady', function() {
  10. alert(el.get('id') + ' has ' + el.get('childNodes').length + ' children');
  11. });
  12.  
//create an Element instance wrapping 'foo';
//'foo' is not yet on the page.
var el = new YAHOO.util.Element('foo');
 
//When 'foo' becomes available, we want to alert
//its id and show the number childNodes; we tell the
//Element instance to do this when the contentReady
//event fires:
el.on('contentReady', function() {
   alert(el.get('id') + ' has ' + el.get('childNodes').length + ' children');
});
 

Manipulating Dom

Most common Dom methods can be applied directy to the Element instance itself:

  1. var el = new YAHOO.util.Element('foo');
  2. //We can access the Dom property hasChildNodes
  3. //directly on the Element instance:
  4. if (el.hasChildNodes()) {
  5. el.removeChild(el.get('firstChild'));
  6. }
  7.  
var el = new YAHOO.util.Element('foo');
//We can access the Dom property hasChildNodes
//directly on the Element instance:
if (el.hasChildNodes()) {
    el.removeChild(el.get('firstChild'));
}
 

Accessing Styles

Element instances can be styled directly via the setStyle method; style properties can be retrieved via getStyle:

  1. var el = new YAHOO.util.Element('foo');
  2.  
  3. //set the color style property of 'foo'
  4. //using the Element instance:
  5. el.setStyle('color', '#f00');
  6.  
  7. //set an event handler using the Element
  8. //instance to alert the value of the
  9. //color style property when 'foo' is clicked:
  10. el.on('click', function() {
  11. alert(this.getStyle('color'));
  12. });
  13.  
var el = new YAHOO.util.Element('foo');
 
//set the color style property of 'foo'
//using the Element instance:
el.setStyle('color', '#f00');
 
//set an event handler using the Element
//instance to alert the value of the 
//color style property when 'foo' is clicked:
el.on('click', function() {
    alert(this.getStyle('color'));
});
 

Support & Community

The YUI Library and related topics are discussed on the on the YUILibrary.com forums.

Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.

More Reading about the YUI Element Utility:

YUI Element on del.icio.us:

bookmark on del.icio.us

be the first to bookmark this page!

Copyright © 2013 Yahoo! Inc. All rights reserved.

Privacy Policy - Copyright Policy - Job Openings