basic-node.mustache revision fb1ecdf65fd4106deb62da339763f2e7670ca0f6
<div class="intro">
<p>This example demonstrates how to retrieve and use a <code>Node</code> instance to access DOM properties.</p>
<p>Click the box to update the content with the <code>tagName</code> of the click target's <code>parentNode</code>.</p>
</div>
<div class="example">
{{>basic-node-source}}
</div>
<h2>Setting up the HTML</h2>
<p>First we need some HTML to work with.</p>
```
<div id="demo">
<p><em>Click me.</em></p>
</div>
```
<h2>Geting a Node Instance</h2>
<p>We will get our <code>Node</code> instance using the <code>one</code> method of our YUI instance which accepts either an HTMLElement or a Selector string.</p>
```
var node = Y.one('#demo p');
```
<h2>Accessing Node Properties</h2>
<p>The properties of a node can be accessed via its <code>set</code> and <code>get</code> methods.</p>
<p>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 <code>Node</code> or <code>NodeList</code> instances.</p>
<p>A <code>click</code> handler will allow us to update the content of our node with the <code>tagName</code> of its <code>parentNode</code>.</p>
<p>Note that the <code>target</code> of the event object will vary depending on where you click. The <code>currentTarget</code> of the event will always be the element that assigned the listener (the <code>P</code> element in this case).</p>
```
var onClick = function(e) {
// e.target === node || #demo p em
var tag = e.target.get('parentNode.tagName');
// e.currentTarget === node
e.currentTarget.one('em').setContent('I am a child of ' + tag + '.');
};
```
<h2>Listening for Node Events</h2>
<p>We will update the node when the <code>click</code> event fires by using the <code>on</code> method to subscribe to the event.</p>
```
node.on('click', onClick);
```
<h2>Complete Example Source</h2>
```
{{>basic-node-source}}
```