2

Basic question.

document.getElementById("yy").onmouseover = hi; //document.getElementsByTagName("li").onmouseover = hi; ... 

In this example, http://jsfiddle.net/8fURz/1/ why does the first line work, but not the second line (when it is un-commented, of course)?

I know I can do this easily with jQuery, just wonderin...

1
  • 1
    Try: jsfiddle.net/8fURz/2 .getElementsByTagName() returns an array of objects, while .getElementById() returns an object, so you have to select a specific index with the former, but not the latter (since it's single by nature). Commented Aug 27, 2012 at 1:44

2 Answers 2

4

Because document.getElementsByTagName("li") return a NodeList, you need to bind event handler to every element of the NodeList.

var list = document.getElementsByTagName("li"); for (var i= 0; i < list.length; i++) { list[i].onmouseover = hi; } 
Sign up to request clarification or add additional context in comments.

Comments

1

Because getElementsByTagName returns a collection of DOM elements. Of course a collection doesn't have a click event. If you want to bind an event to every element in the collection, you would simply loop through the collection and add a handler to every DOM element in the collection.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.