2

Hello I am trying to update the src of an iframe with javascript, below is the code I am trying. When I try to execute the code it fails as if an error occured, and stops executing code when I call this line.

document.getElementById('logviewer').src = "www.yahoo.com";

Example code:

<iframe src="" id="logviewer"/>
<script type="javascript/text">
document.getElementById('logviewer').src = "www.yahoo.com";
alert('Loaded Yahoo');
</script>

You can see the src doesn't change and the alert doesn't show.

Thanks ahead of time for your answers!

4
  • possible duplicate of Why does jQuery or a DOM method such as `getElementById` not find the element? Commented Aug 25, 2013 at 20:04
  • 1
    @PatrickEvans Nope, not exactly the problem.. Commented Aug 25, 2013 at 20:08
  • Mind marking the right answer? Thanks. Commented Aug 26, 2013 at 7:37
  • There is no duplicate. The code does not run because the type is wrong. Commented Aug 27, 2013 at 4:52

1 Answer 1

2

There are some major issues in your code:

  • script mime-type should be text/javascript not javascript/text
  • iframe tag should have a closing tag...shortopentags are not supported. This is because contant in between iframe tags is shown when the browser does not support iframes. Your code meant that the script tag ended up in this section instead.
  • document might not be ready when that code runs (you need to put your code in a domready event), this is basically what Patrick is talking about. I think it's a very relevant cause as well.

Here's your code in a working condition: http://jsfiddle.net/4EMdn/

Sign up to request clarification or add additional context in comments.

1 Comment

the code shouldn't even be executed as javascript if it has an unknown type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.