Javascript DOM HTML IFrame contentDocument Property

Introduction

A cross browser example on how to change the background color of the document contained in an iframe:

Click the button to change the background color of the document contained in the iframe.

View in separate window

<!DOCTYPE html>
<html>
<body>

<iframe id="myframe" src="https://www.java2s.com"></iframe>
<p id="demo"></p>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {/*from   w w  w  . j  av  a  2  s  .c  om*/
  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 contentDocument property returns the Document object generated by an iframe element.

We can use it in the host window to access the Document object for an iframe element.

We can only accessed document located in the same domain.

Return Value: A reference to the document object.

If there is no document, the returned value is null

Another example of how to access the document of an iframe to change the background color:

Click the button to change the background color of the document contained in the iframe.

View in separate window

<!DOCTYPE html>
<html>
<body>

<iframe id="myframe" src="https://www.java2s.com"></iframe>
<p id="demo"></p>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {/* w  w w. 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>



PreviousNext

Related