1

I'm new to JavaScript and I cannot understand why my html isn't changing?

I have an Iframe and I'm trying to change the .innerHTML of the span class that the Iframe has created in the DOM.

In the DOM structure, the class is called <span class="weather-location">China</span>

I'm just trying to access this by changing it's innerHTML to Taiwan instead.

here is my code:

<html>
<head>
<title>test</title>
</head>
<body onload="myFunction()">

<iframe class="weather" width="100%" height="600px" frameBorder="0" 
src="(this is my iframe src code)></iframe>

<script type="text/javascript">
   function myFunction() {
      document.getElementsByClassName("weather-location")[0].innerHTML = "Taiwan";
   }
</script>
</body>
</html>

When I test it in the console log, it brings up that weather-location as [] but whats also bizarre is when I use the selector tool to hover on that weather-location class and go back and re-type in the code it in the console, it changes the class how I wanted?

Also, I don't know if this helps but when it shows up as [] in chrome a little i box pops up saying "value below was evaluated just now".

Curious13
  • 329
  • 2
  • 23
  • 1
    See https://stackoverflow.com/questions/478078/accessing-a-form-that-is-in-an-iframe - a frame has its own `document`. – le_m Jun 07 '17 at 00:02
  • Imagine this. I call some banking page into mine, via iframe, full page. Than I go around and change elements within that iframe :) just imagine. Fun apart, it's doable if you have *API* access to that iframe or it's actually from your own domain... – Roko C. Buljan Jun 07 '17 at 00:11
  • You need to have the script inside the frame. – Allen King Jun 07 '17 at 00:16

1 Answers1

2

You can't change the innerHTML of iframes if it's on another domain.

https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe

This kind of iframe is like a window into another webpage you have no control over.

If it is on the same domain you can use something like

var ifr = document.getElementById( yourIframeId );
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.getElementById( yourFormId );

SO Question: accessing a form that is in an iframe

Credit to : @le_m

Josh
  • 718
  • 10
  • 25