How to change or manipulate iframe content using JavaScript

← PrevNext →

In my previous article I have shared an example explaining how to get HTML elements within an iframe. So, if you can get iframe elements dynamically, then you can manipulate or change iframe content too. I'll show you how to do this using JavaScript.
See this demo
The Script and the Markup
<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>
Try it

See this line in the above script... let doc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;

There are two different iframe properties, "contentDocument" and contentWindow.document within a ternary operator (a condition). Which ever condition is "true", returns a document (the HTML content) within the iframe.

Now, add the code to check the iframe "document" in your browser's console window.

console.log (frame.contentWindow.document);

So, once I have access to the HTML (or the document) within the iframe, I can manipulate or alter or change the content of any element. Not just the content, I can change or alter the style attributes too. However, I should know or have access to the id of the element that I want to change.

← PreviousNext →