AlgoRythm
AlgoRythm

Reputation: 168

copy contenteditable HTML to iframe

I'm making an HTML reader inside HTML (For reasons...)

I used to be able to do this fine. I took the value of a text area and applied it to an iframe, like this:

    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 style (The textarea did NOT like the background-attachment:local; property) So I had to change it to a div with contenteditable and here is 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 over to the iframe... how do I fix this? No html copies over if I use the .innerHTML instead of the .textContent. It's annoying. One thing is always wrong...

Native JavaScript (For reasons and purposes)

Upvotes: 3

Views: 153

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

jsBin demo

use innerHTML to get the whole inner HTML String:

document.getElementById('page').innerHTML;

that will take the complete Paragraph out of your elementwith al lthe 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();

Upvotes: 1

Related Questions