Reputation: 1616
I am collecting all images elements from the document var listen = document.getElementsByTagName('img');
which results in an array. Now I have to specify listen[0]
, listen[1]
, listen[2]
, listen[3]
etc to listen for events on a element from this array. The question is is there any way to just do something like listen[any item from this array]
, or a function. Just to don't have to specify every element to listen on manually.
Now I have to do something like this, for every array item:
listen[3].click = function() {};
Upvotes: 0
Views: 284
Reputation: 72692
Depending on what it is exactly what you want and what the DOM looks like you may want to use an event listener higher up the DOM tree somewhere instead of create a lot of listeners:
document.addEventListener('click', function(e) {
if (e.target.nodeName !== 'IMG') {
return;
}
alert('img clicked');
});
Demo: http://jsfiddle.net/APSMT/1/
Note that I have attached the event listener to document
, but if you can make it more specific you should
Upvotes: 3
Reputation: 26043
With a reasonable new browser you can use Array.forEach:
[].forEach.call(document.getElementsByTagName('img'), function (img) {
el.addEventListener('click', callback);
});
Or "old skool" (and maybe even better readable):
var imgs = document.getElementsByTagName('img');
for (var i = 0, len = imgs.length; i < len; ++i) {
imgs[i].addEventListener('click', callback);
}
Reading the HTMLCollection.length
only once can give a speed-up. It will never be slower.
You should not create a Function object for every iteration:
// Don't
for (...) {
img[i].onclick = function () { ... }
}
// Do
function onclick () {
// `this` will be img[i]
}
for (...) {
img[i].onclick = onclick;
}
Upvotes: 1