Reputation: 293
Why is that adding an event to the document.querySelector('li')
works fine but
Adding an event to the document.getElementsByTagName('li').childNodes
Results in error and how to overcome this problem and attach events to all
Its child nodes successfully, I know using childNodes
creates an array but how do we add it. Should I use a for
loop ?
Upvotes: 2
Views: 3595
Reputation: 35670
You can add an event to an element but not to a collection.
You can access childNodes
from an element but not a collection. Note that childNodes
may include text nodes, which don't support event handlers.
What you want is document.querySelectorAll()
, which creates a collection of elements based on a CSS selector.
You can iterate through the collection using a for
loop, adding event listeners along the way:
var nodes= document.querySelectorAll('li > *');
for(var i = 0 ; i < nodes.length ; i++) {
nodes[i].addEventListener('click', function() {
alert('You clicked ' + this.textContent);
});
}
li * {background: orange;}
<ul>
<li>Lorem <em>ipsum</em> dolor <strong>sit</strong> amet</li>
<li>Consectetur <em>adipiscing</em> elit</li>
<li>beatae <em>vitae</em> dicta <strong>sunt</strong></li>
</ul>
Upvotes: 3
Reputation: 2714
for(var element : document.getElementsByTagName('li')) {
Event.observe(element, "click", function(){...});
}
Upvotes: 1