Copy content HTML to iframe

I am making an HTML reader inside HTML (for reasons ...)

I used to be able to do it well. I took the value of the textarea and applied it to the iframe like:

    var x = document.getElementById("HTMLdocument");
    var y = (x.contentWindow || x.contentDocument);
    if (y.document)y = y.document;
    y.body.innerHTML = document.getElementById('page').value;

      

But there was something to do with styling (the textbox didn't like the background-attachment: local; property) So I had to change it to a div with contenteditable

and here's my new code:

    var x = document.getElementById("HTMLdocument");
    var y = (x.contentWindow || x.contentDocument);
    if (y.document)y = y.document;
    y.body.innerHTML = document.getElementById('page').textContent;

      

But only basic HTML copies in the iframe ... how can I fix this? There are no html copies if I use .innerHTML instead of .textContent. This is annoying. One thing is always wrong ...

Native JavaScript (for reasons and purposes)

+3


source to share


1 answer


jsBin demo

use innerHTML

to get all inner HTML string:

document.getElementById('page').innerHTML;

      

which will output from a Paragraph

complete Paragraph

element with other related styles:



<div id="page" contenteditable>
    <p style="color:red">Foo</p>
</div>

      

var x = document.getElementById("HTMLdocument");
var y = (x.contentDocument || x.contentWindow);
if (y.document) y = y.document;

// Might work in Chrome but will fail in Firefox
// y.body.innerHTML = document.getElementById('page').innerHTML;

// So rather:
y.open();
y.write( document.getElementById('page').innerHTML );
y.close();

      

+1


source







All Articles