Javascript Reference - HTML DOM IFrame contentDocument Property








The contentDocument property returns the Document object generated by a frame or iframe element.

Browser Support

contentDocument Yes Yes Yes Yes Yes

Syntax

var v = iframeObject.contentDocument 

Return Value

A reference to the document object. If there is no document, null is returned.





Example

A crossbrowser example on how to change the background color of the document contained in an iframe.


<!DOCTYPE html>
<html>
<body>
<iframe id="myframe" src="http://example.com"></iframe>
<p id="demo"></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from  ww w.ja v  a 2s.co  m-->
    var x = document.getElementById("myframe");
    var y = (x.contentWindow || x.contentDocument);
    if (y.document)y = y.document;
    y.body.style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to access the document of an iframe to change the background color.


<!DOCTYPE html>
<html>
<body>
<iframe id="myframe" src="http://example.com"></iframe>
<p id="demo"></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!-- w  ww  .j  a  v  a 2  s .  c  o m-->
    var x = document.getElementById("myframe");
    var y = x.contentDocument;
    y.body.style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows: