This example demonstrates how to use a NodeList instance to work with multiple nodes.
- Click me
- Click me
- Click me
- Click me
Setting up the Node
First we need some HTML to work with.
<ul id="demo"> <li>lorem</li> <li>ispum</li> <li>dolor</li> <li>sit</li> </ul>
Geting a NodeList Instance
We will use the all
method of our YUI instance to get a NodeList instance to work with.
var nodes = Y.all('#demo li');
Accessing NodeList Properties
As with Node, simple type of properties (strings, numbers, booleans) pass directly to/from the underlying HTMLElement, however properties representing HTMLElements return Node instances.
In this example, we will listen for a click
event to trigger the property change.
Note that the context of the handler is set to the NodeList, so this
refers to our NodeList instance. The currentTarget
property of the event object is set to the current Node instance.
var onClick = function(e) { // this === nodes this.setContent('thanks from all of us!'); // e.currentTarget === #demo li e.currentTarget.setStyle('backgroundColor', 'green'); };
Prefer node.delegate()
over nodelist.on()
Sometimes you need to create individual subscriptions for each Node in a NodeList (as is done in this example), but usually it's preferable to use event delegation.
Complete Example Source
<ul id="demo"> <li>Click me</li> <li>Click me</li> <li>Click me</li> <li>Click me</li> </ul> <script type="text/javascript"> YUI().use('node', function(Y) { var nodes = Y.all('#demo li'); var onClick = function(e) { // this === nodes this.setContent('thanks from all of us!'); // e.currentTarget === #demo li e.currentTarget.addClass('highlight'); }; nodes.on('click', onClick); }); </script>