2

As a challange of mine, i decided to do a little Code Player like jsfiddle, i have done all, but my problem come when i try to exec JS, when i try to call an element inside the iframe like this:

document.getElementById("hola").innerHTML="nohola";

It just says:

TypeError: document.getElementById(...) is null

There's a live demo: jsfiddle.net

How i can inject js into the iframe and call elements inside it?

Angel
  • 29
  • 6

1 Answers1

1

The problem is that your script tag is created by the document object of your main document.

var script = document.createElement('script');

Which will make the javascript inside it scoped to the main document. You have to create it using the document object of the iframe, so that the javascript will be scoped to the iframe.

You can access the iframe document through the contentWindow.document property like this:

Check this fiddle

function runJs() {
      var iframe = document.getElementById('resultIframe');
      var frameDoc = iframe.contentDocument || iframe.contentWindow.document;
      var body = $('body', frameDoc);
      var code = $('#codeJs').find('textarea').val();
      var script = frameDoc.createElement("script");           // not document.createElement('script');
      script.setAttribute("type", "text/javascript");
      script.textContent = code; 
      body[0].appendChild(script); 
}

Also see these answers

Community
  • 1
  • 1
Ahmad Ibrahim
  • 1,915
  • 2
  • 15
  • 32