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>
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>
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>