Html:

<ul> <li>Example li</li> <li>Example li</li> <li>Example li</li> <li>Example li</li> <li>Example li</li> <li>Example li</li> <li>Example li</li> </ul> 

Js:

 var ul = document.getElementsByTagName('ul'); ul.onclick = function(event) { alert(); } 

alert not displayed when clicking on the elements <li> But if you assign the ul id to the element and search through document.getElementById , then the code will work. Why is that?

  • var ul = document.getElementsByTagName('ul')[0] - Alexander Igorevich
  • Why does this work that way? Why specify an index? - Sergey Alekseev
  • and add: window.onload = function () {ваш код} - user33274

1 answer 1

getElementsByTagName returns a collection of elements that were found in the document. To access a specific node, you need to specify its index.

var ul = document.getElementsByTagName('ul')[0]

getElementById returns directly a link to the document's search node.

  • Now everything is clear. Thank ! - Sergey Alekseev