Reputation: 105
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
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
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
Reputation: 943214
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.Upvotes: 2