Mark
Mark

Reputation: 105

Confusion about onclick function

Beginner JS here, hope anyone could explain this to me.

1) Why does this not work:

var allSpans = document.getElementsByTagName('span');
allSpans.onclick = function() {
 alert('hoo'); 
};

2) or if I have all the innerHTML from spans in an array and I try this:

var allSpans = document.getElementsByTagName('span');
var arrayNumbers = [];

for (var i = 0; i < allSpans.length; i++) {
  var operator = allSpans[i].innerHTML; 
}
arrayNumbers.onclick = function() {
 alert('hoo'); 
};

Upvotes: 0

Views: 69

Answers (3)

dcoates
dcoates

Reputation: 396

To answer your first question, you have to add this on each node instead of the nodeList, which is what you're getting when you call document.getElementsByTagName. What you're looking for is:

for(var i = 0; i < allSpans.length; i++){
  allSpans[i].onClick = function(){
    alert('hoo');
  };
}

You have a similar issue in the second question, except it doesn't appear as if you're actually adding anything to the arrayNumbers array, so even if you looped through that, you wouldn't get the expect events on click.

Upvotes: 0

Luketep
Luketep

Reputation: 181

You have to iterate through the returned list

var allSpans = document.getElementsByTagName('span');

for ( var i = 0; i < allSpans.length; i += 1 ) {
    allSpans[i].onclick = function (event) {
         alert('hoo'); 
    };
}

Upvotes: 1

Quentin
Quentin

Reputation: 943214

  1. onclick is a property of HTMLElementNode objects. getElementsByTagName returns a NodeList. Assigning a property to a NodeList doesn't assign it to every member of that list.
  2. Exactly the same, except you are dealing with an Array instead of a NodeList.

Upvotes: 2

Related Questions