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.
Here's the script.
<body> <iframe src="https://www.encodedna.com/frametools/recentposts.aspx" 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>
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>
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>