Access elements inside iframe and Tags body with JavaScript

I am writing a GreaseMonkey script that changes the attribute of an element with a specific identifier, but I am having some problems with its access due to the unconventional HTML hierarchy. Here is the relevant HTML:

<body> ... <iframe id="iframeID"> <html> ... <body id="bodyID" attribute="value"> ... </body> ... </html> </iframe> ... </body> 

Where attribute is the attribute I'm trying to change.

At first, not realizing that I was working with an iframe tag and a nested body tag, I tried this:

 document.getElementById('bodyID').setAttribute("attribute","value") 

While this worked fine in Firefox, Chrome tells me that I cannot set the null attribute, assuming it cannot find any elements with id bodyID . How to change this attribute in a friendly browser?

+4
source share
2 answers

First you need to pull out the <iframe> document:

 document.getElementById('iframeID').contentDocument .getElementById('bodyID').setAttribute("attribute","value"); 

Live demo

By the way, if you want to get a <body> node, you do not need to specify an id or something like that, just:

 document.body 

In your case, this is an <iframe> document:

 document.getElementById('iframeID').contentDocument.body.setAttribute("attribute","value"); 

A lot easier ... Isn't it?

+8
source

The best way, IMO, to do this is to listen to the load event emitted by the iFrame, and then look into the iFrame DOM as needed. This ensures that you have access to the iFrame DOM when you need it, and take a picture.

 $('#iframeID').on('load', function () { alert('loaded'); // iFrame successfully loaded var iFrameDoc = $('#iframeID')[0].contentDocument; // Get the iFrame document $('body', iFrameDoc).attr('attribute', 'new value'); // Get the 'body' in the iFrame document and set 'attribute' to 'new value' }); 
+1
source

All Articles