0

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'); 
};
Mark
  • 105
  • 1
  • 3
  • 8

3 Answers3

2
  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.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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'); 
    };
}
Luketep
  • 181
  • 1
  • 9
  • Alright, I get it, but in JSlint the error: Don't make functions within a loop. occurs? Is this something to look at or does it not matter? – Mark Nov 28 '13 at 19:05
  • 1
    @Marek: It doesn't matter in your example, but it's something you have to aware of. See http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example. – Felix Kling Nov 28 '13 at 19:11
0

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.

dcoates
  • 376
  • 3
  • 4