How do I use the JavaScript DOM to apply onclick events to links inside of an iframe?
Here’s what I’m trying that isn’t working:
document.getElementById('myIframe').contentDocument.getElementsByTagName('a').onclick = function();
No errors seem to be thrown, and I have complete control of the stuff in the iframe.
Here is some code to test and see if I can at least count how many div‘s are in my iframe.
// access body var docBody = document.getElementsByTagName('body')[0]; // create and load iframe element var embed_results = document.createElement('iframe'); embed_results.id = 'myIframe'; embed_results.setAttribute('src', 'http://www.mysite.com/syndication/php/embed.php'); // append to body docBody.appendChild(embed_results); // count the divs in iframe and alert alert(document.getElementById('myIframe').contentDocument.getElementsByTagName('div').length);
It is possible for an iFrame to source content from another website on a different domain.
Being able to access content on other domains would represent a security vulnerability to the user and so it is not possible to do this via Javascript.
For this reason, you can not attach events in your page to content within an iFrame.