Home

SiteMap

How to get HTML element from an iframe using JavaScript

← PrevNext →

Let us assume, I have an iframe on my web page and I want to get specific elements, like <h2> etc., from the web page in the iframe, using JavaScript.

Below is a web page embeded inside an iframe element, for example. I want to get the "first" <h2> element (the header which reads "Releted Posts") from page in the iframe.

The iframe... 👇

Here's the script.

<body>
  <iframe src="" 
    id="theFrame">
  </iframe>
</body>
<script>
    window.onload = function () {
        const frame = document.getElementsByTagName("iframe")[0];
        let doc = (frame.contentDocument)  ? frame.contentDocument  : frame.contentWindow.document; 
        let ele = doc.getElementsByTagName('h2')[0];
        console.log(ele.innerHTML);
    }
</script>
Try it

Its a simple code. All you have to know is, which element you want to get (or extract) from the page in the iframe.

You can even manipulate an element's content or change the element's style etc. For example, I want the change <h2> value (the header text), dynamically.

<script>
 window.onload = function () {
    const frame = document.getElementsByTagName("iframe")[0];
    let doc = (frame.contentDocument)  ? frame.contentDocument  : frame.contentWindow.document; 
    let ele = doc.getElementsByTagName('h2')[0];

    ele.innerHTML = 'Articles you may like';		// change text of the <h2> element.
  }
</script>
Try it

I just changed the default text of <h2> to a new text.

You can change/alter the default style, that is asigned to the element, to a new style. For example,

<script>
 window.onload = function () {
    const frame = document.getElementsByTagName("iframe")[0];
    let doc = (frame.contentDocument)  ? frame.contentDocument  : frame.contentWindow.document; 
    let ele = doc.getElementsByTagName('h2')[0];

    ele.innerHTML = 'Articles you may like';        // change text of the <h2> element.
    ele.style.color = 'red';		// default color was black, now its red.
  }
</script>

← PreviousNext →