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.
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.
To use the Element Utility, include the following source files in your web page with the <script> tag:
<!-- 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>
<!-- 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>
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.
To create a new Element instance, pass either the ID of the element or a reference to the HTMLElement to the Element constructor:
var el = new YAHOO.util.Element('foo');
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:
//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); });
//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); });
<!--markup for foo--> <div id="foo"> <ul> <li>lorem</li> <li>ipsum</li> <li>dolor</li> <li>sit</li> </ul> </div>
<!--markup for foo--> <div id="foo"> <ul> <li>lorem</li> <li>ipsum</li> <li>dolor</li> <li>sit</li> </ul> </div>
This section describes several common uses of Element. It contains these subsections:
All Element events are applied using the addListener
method (alised as on
and can be removed with removeListener
.
//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);
//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.
delegate
MethodEvent 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:
<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>
<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>
Consider the following HTML.
<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>
<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>
.
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");
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");
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')
.
//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');
//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:
//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'); });
//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'); });
Most common Dom methods can be applied directy to the Element instance itself:
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')); }
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')); }
Element instances can be styled directly via the setStyle
method; style properties can be retrieved via getStyle
:
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')); });
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')); });
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.
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.
be the first to bookmark this page!
All YUI 2.x users should review the YUI 2.8.2 security bulletin, which discusses a vulnerability present in YUI 2.4.0-2.8.1.
Copyright © 2013 Yahoo! Inc. All rights reserved.