In this guide, I'll show you step-by-step how to manipulate iframe elements using JavaScript. Whether you're looking to inject new content or adjust styles, mastering iframe interactions can enhance your web development projects.
<style> #theFrame { width: 100%; height: 350px; border:dashed 2px #099; } </style> </head> <body> <p> Type here... <input type='text' onkeyup='change_iframe_content(this)' id='t1' value=''> </p> <iframe src="https://www.encodedna.com/javascript/contenteditable-div.htm" id="theFrame"></iframe> </body> <script> let change_iframe_content = (ele) => { const frame = document.getElementsByTagName("iframe")[0]; let doc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document; let iframe_ele = doc.getElementById('editor'); iframe_ele.innerHTML = ele.value; } </script>
See this code in the above script: 👇
let doc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
Understanding contentDocument and contentWindow.document in an Iframe
There are two key properties used to access the document inside an iframe: "contentDocument" and contentWindow.document.
These properties are used within a ternary operator to check for availability. Whichever condition evaluates to true, it returns the iframe's document (its HTML content), allowing manipulation and interaction with elements inside the iframe.
By dynamically selecting the appropriate property, you ensure seamless access to the iframe's content, making it easier to modify styles, update elements, or inject new data.
Add the below code to check the iframe "document" in your browser's console window.
console.log (frame.contentWindow.document);
Once I have access to the HTML document within an iframe, I can dynamically manipulate its elements. This includes altering content, injecting new data, or adjusting style attributes to customize the appearance.
However, to modify a specific element inside the iframe, I must know or have access to its ID. Identifying the correct element ensures precise changes, whether it's updating text, tweaking styles, or interacting with iframe components effectively.
By leveraging JavaScript, I can seamlessly enhance iframe content and styling, improving interactivity and user experience.