This example demonstrates how insert content when working with NodeList
instances.
Clicking a box will update its content.
- foo
- bar
Setting up the NodeList
First we need some HTML to work with.
<ul id="demo"> <li>foo</li> <li>bar</li> </ul>
Adding Content
Next we will add a handler to run when the event is fired. In our handler we will add content to the node.
Note that the event handler receives an event object with its currentTarget
set to the current Node instance, and the actual node clicked as the target
. The context of the handler is the NodeList instance, so this
refers to our NodeList instance.
Note also that prepend
inserts content as the firstChild
of the Node instance, append
inserts content as the lastChild
, and insert
places content before the specified node or childNode index.
var onClick = function(e) { var node = e.currentTarget; node.prepend('<em>prepended</em> '); // added as firstChild node.append(' <em>appended</em>'); // added as lastChild node.insert(' <strong>before last child</strong> ', node.get('lastChild')); // added before lastChild node.insert(' <strong>before childNodes[1]</strong> ', 1); // added before childNodes[1] };
Attaching Events
We can assign our handler to all of the items by using the all
method to get a NodeList
instance and using the on
method to subscribe to the event.
Y.all('#demo li').on('click', onClick);
Complete Example Source
<ul id="demo"> <li>foo</li> <li>bar</li> </ul> <script type="text/javascript"> YUI().use('node', function(Y) { var onClick = function(e) { var node = e.currentTarget; node.prepend('<em>prepended</em> '); // added as firstChild node.append(' <em>appended</em>'); // added as lastChild node.insert(' <strong>before last child</strong> ', node.get('lastChild')); // added before lastChild node.insert(' <strong>before childNodes[1]</strong> ', 1); // added before childNodes[1] }; Y.all('#demo li').on('click', onClick); }); </script>