Home

SiteMap

How to get HTML element from an iframe using JavaScript

← PrevNext →

Let us assume, I am using an iframe to show a web page and I want to get specific elements (tags), like <h1> etc., from the web page dynamically. Let me show you a JavaScript trick.

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

The iframe 👇, embeded in it is another HTML page. I would like to extract the H1 element text.

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('h1')[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.

Change or Modify iframe content

You can even manipulate an element's content or change the element's style etc. For example, I want the change <h1> 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('h1')[0];

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

I just changed the default text of <h1> 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('h1')[0];

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

← PreviousNext →