Example: Using NodeList - Simple

This example demonstrates how to use a NodeList instance to make it easy to manipulate multiple nodes at once.

Click us.
  • box
  • box
  • box
  • box
  • box

Setting up the Node

First we need some HTML to work with.

Click us.
<ul class="box-row">
    <li>box</li>
    <li>box</li>
    <li>box</li>
    <li>box</li>
    <li>box</li>
</ul>

CSS

CSS to make boxes in horizontal row

<style>
.example .box-row li{
    display: inline-block;
    zoom: 1; *display: inline; /* IE < 8: fake inline-block */
    width: 100px;
    line-height: 3em;
    text-align: center;
    margin: 0.5em 1em 0.5em 0;
    border: solid 1px #ccc;
    background-color: #F4E6B8;
    cursor: pointer;
}
</style>

Geting a NodeList Instance

We will use the all method of our YUI instance to get a NodeList instance to work with.

var boxes = Y.all('.box-row 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 handleBoxClick = function(e) {
    // this === boxes, which is a NodeList
    this.setHTML('neener');
    this.setStyle('backgroundColor', '#F4E6B8');

    // e.currentTarget === .box-row li, just the one that was clicked
    e.currentTarget.setHTML('ouch!');        
    e.currentTarget.setStyle('backgroundColor', '#C4DAED');
};    
boxes.on('click', handleBoxClick);

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 Simple Box Example Source

<style>
.example .box-row li{
    display: inline-block;
    zoom: 1; *display: inline; /* IE < 8: fake inline-block */
    width: 100px;
    line-height: 3em;
    text-align: center;
    margin: 0.5em 1em 0.5em 0;
    border: solid 1px #ccc;
    background-color: #F4E6B8;
    cursor: pointer;
}
</style>

Click us.
<ul class="box-row">
    <li>box</li>
    <li>box</li>
    <li>box</li>
    <li>box</li>
    <li>box</li>
</ul>

<script>
YUI().use('node', function(Y){
    var boxes = Y.all('.box-row li');

    var handleBoxClick = function(e) {
        // boxes is a NodeList
        boxes.setHTML('neener');
        boxes.setStyle('backgroundColor', '#F4E6B8');
    
        // e.currentTarget === .box-row li, just the one that was clicked
        e.currentTarget.setHTML('ouch!');        
        e.currentTarget.setStyle('backgroundColor', '#C4DAED');
    };    
    Y.one('.box-row').delegate('click', handleBoxClick, 'li');
});
</script>