0

I have an html element:

<img alt="" src="../Images/ERROR.jpg" id="live1x4" height="288" style="width: 360px;
                                                display: block;" /

If i refer to this control in javascript which is in the same html page:

live1x4.src = src;

Where src is the location of an image the script works.

If move that javascript to an external js file I get 'live1x4' is undefined.

This occurs ONLY in Internet Explorer.

Wjat can be causing this error?

3
  • 3
    I'd recommend to use document.getElementById('live1x4'). You also have to make sure that you are trying to refer to the element when it exists (not before). Commented Apr 1, 2014 at 18:39
  • 1
    If it works in one file, the element is namespaced to the global object, so the browser should do the same thing in the other file, so chances are high that the other file runs before the element is available, or it's simply in the wrong scope. You should be using getElementById anyway IMO. Commented Apr 1, 2014 at 18:43
  • People... thank you for the lesson :) Commented Apr 1, 2014 at 18:46

2 Answers 2

1

You have to target your element, not simply refer to the ID:

document.getElementById("live1x4").src  = ....
Sign up to request clarification or add additional context in comments.

Comments

0

The reason is that the JavaScript code is executed before the img element has been parsed. Whether this happens depends on many things. There are different ways to ensure that it does not happen. A simple way is to wrap your code inside an even handler that is triggered after the document has been loaded:

window.onload = function() {
   // your code here, here all elements are available, e.g.:
   live1x4.src = src;
}

It is generally regarded as bad coding style to use id attribute values as if they were global variables (partly because they stop working ifsynonymous global variables are added), so document.getElementById("live1x4") is preferable to live1x4. However, this is a different topic.

Comments

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.