I cant figure out why this isn’t working. It’s probably something simple. The iframe is from the same domain as parent page.
I know I can use jQuery, but I want to learn to do it in pure JavaScript.
My code so far:
document.getElementById('my_iframe').onload = function() {
document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img').onclick = function() {
alert("image in iframe was clicked");
}
}
Forget the frame business for a second, and look at this code:
Will that ever work? No. You are getting an object (a
NodeList, to be precise) containing all theimgelements in the document. You are adding anonclickproperty to that object. Not to the elements themselves: to an object that points to them. The function will never be fired because it is never applied to any elements.You should do exactly the same as you normally would: loop though all the images you’ve found and apply the function to them individually.