YUI 3.x Home -

YUI Library Examples: Node: Node Basics

Node: Node Basics

This example demonstrates how to get and use a Node instance to access DOM properties.

Click the box to update the content of with the tagName of the click target's parentNode.

Click me.

Setting up the HTML

First we need some HTML to work with.

  1. <div id="demo">
  2. <p><em>Whose child am I?</em></p>
  3. </div>
<div id="demo">
    <p><em>Whose child am I?</em></p>
</div>

Geting a Node Instance

We will get our Node instance using the one method of our YUI instance which accepts either an HTMLElement or a Selector string.

  1. var node = Y.one('#demo p');
var node = Y.one('#demo p');

Accessing Node Properties

The properties of a node can be accessed via its set and get methods.

In most cases, simple type of properties (strings, numbers, booleans) pass directly to/from the underlying DOM node, however properties representing other DOM nodes return Node or NodeList instances.

A click handler will allow us to update the content of our node with the tagName of its parentNode.

Note that the target of the event object will vary depending on where you click. The currentTarget of the event will always be the element that assigned the listener (the P element in this case).

  1. onClick = function(e) {
  2. var tag = e.target.get('parentNode.tagName'); // e.target === node || #demo p em
  3. e.currentTarget.one('em').setContent('I am a child of ' + tag + '.'); // e.currentTarget === node
  4. };
onClick = function(e) {
    var tag = e.target.get('parentNode.tagName'); // e.target === node || #demo p em
    e.currentTarget.one('em').setContent('I am a child of ' + tag + '.'); // e.currentTarget === node
};

Listening for Node Events

We will update the node when the click event fires by using the on method to subscribe to the event.

  1. node.on('click', onClick);
node.on('click', onClick);

Full Script Source

  1. YUI().use('node', function(Y) {
  2. var node = Y.one('#demo p');
  3.  
  4. var onClick = function(e) {
  5. var tag = e.target.get('parentNode.tagName'); // e.target === node || #demo p em
  6. e.currentTarget.one.setContent('I am a child of ' + tag + '.'); // e.currentTarget === node
  7. };
  8.  
  9. node.on('click', onClick);
  10. });
YUI().use('node', function(Y) {
    var node = Y.one('#demo p');
 
    var onClick = function(e) {
        var tag = e.target.get('parentNode.tagName'); // e.target === node || #demo p em
        e.currentTarget.one.setContent('I am a child of ' + tag + '.'); // e.currentTarget === node
    };
 
    node.on('click', onClick);
});

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings