/    Sign up×
Community /Pin to ProfileBookmark

Iframe document write doesn’t update JavaScript

Here’s a basic HTML editor:


iframe {
 width: 400px;
 height: 300px;




var textarea = document.querySelector('textarea'),
 iframe = document.querySelector('iframe');

function preview() {
 var iframeDoc = iframe.contentDocument;

textarea.addEventListener('input', preview);


It updates the HTML and CSS you put in the textarea, but you can’t use JavaScript const or let variables as it throws the following syntax error as soon as you edit the inserted code:

Identifier * has already been declared

To see what I mean, insert the following sample code in the textarea:

<!doctype html>
<html lang="en">
 <title>Sample Code</title>
 const p = document.querySelector('p');
 p.style.color = 'blue';

Now change Hello! to Hello, world!, or blue to red.

What’s the solution so the user can keep editing the code without getting that error?

to post a comment

0Be the first to comment 😎



Help @Rain_Lover spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.15,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ

legal: ({
terms: of use,
privacy: policy
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,