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";
}

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

Usage:




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

© 2019 4codev

Created with love by Sil.