简体   繁体   中英

Adding Events for all the child nodes

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 ?

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> 

for(var element : document.getElementsByTagName('li')) {
  Event.observe(element, "click", function(){...});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM