Get an element of the iframe with Javascript

To get an element of an iframe with Javascript, we use the contentWindow method like the example codes below:

function changeColorHeaderIframe() {
  const iframe = document.getElementById("testIframe");
  const iframeHeader = iframe.contentWindow.document.getElementsByTagName("h1")[0];
  iframeHeader.style.color = "red";
}
Copy this code

In the codes above, we will get the first <h1> element inside the iframe and change its color to red.

Usage:


<iframe id="testIframe" src="https://wwww.4codev.com"></iframe>
<button onclick="changeColorHeaderIframe()">Click me</button>


Copy this code


So easy, with this example, you can get any element of the iframe.

© 2019 4codev

Created with love by Sil.