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 ?
Asked
Active
Viewed 2,910 times
2

am guru prasath
- 345
- 1
- 7
- 28
2 Answers
3
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>

Rick Hitchcock
- 35,202
- 5
- 48
- 79
1
for(var element : document.getElementsByTagName('li')) {
Event.observe(element, "click", function(){...});
}

Eduard Void
- 2,646
- 1
- 13
- 13
-
or if you want to add to all child elements of all li tags wrap this into another for loop – Eduard Void Jun 23 '15 at 14:31