Search code examples
javascriptframegetelementbyidframeset

TypeError:Cannot read property 'getElementById' frameset


I have a simple code that refreshes the main page each time there is a new version, but it only works in Internet Explorer. In other browsers I get the following error:

Uncaught TypeError: Cannot read property 'getElementById' of undefined line 24

Here is my code:

    <html>

    <script type="text/javascript">
     var num=0;
     var currVersion;
     var started=false;

     function startLoad() {
     var url= "version_telemark.html?"+ (++num);
        window.version.navigate(url);
     }

     function endLoad() {
       if (started) {
         var newVersion = version.document.getElementById("version").value;
         if (newVersion != currVersion) {
           currVersion=newVersion;
           var url  = "telemark.html?"+ (++num);
             window.pane.navigate(url);
         }
       }
     }
     function start() {
        currVersion = version.document.getElementById("version").value;
       started=true;
       setInterval("startLoad()", 200);
     }
    </script>

  <frameset    onload="start()"  cols="40%,100%">
    <frame id="version"   src="version_telemark.html"/>
    <frame id="pane" src="telemark.html" />
  </frameset>

</html>

and in my other file I only have that I wish to edit I have:

<input id="version" name="version" type="textbox" value="700">

and my other file that has the design just has tables but we wont need to add anything there.


Solution

  • Two things:

    1. Your code is relying on the automatic global that browsers create for elements that have ids on them, by using version as a global variable without declaring or initializing it. Perhaps for some reason, the automatic global isn't working on browsers other than IE. I don't like to rely on them anyway, it's too easy to shadow them, so I suggest getting the element on purpose by adding this near the top of your script:

      var version = document.getElementById("version");
      

      But your comment on the question suggests that it's not this, but #2 below:

    2. You may need vesrion.contentDocument rather than version.document in your currVersion = version.document.getElementById("version").value; and similar lines; perhaps JavaScript's curiously-powerful || operator:

      var versionDoc = version.document || version.contentDocument;
      // ...and then
      currVersion = versionDoc.getElementById("version").value;
      // ...and so on
      

    Side note: Just to keep yourself and whoever has to maintain the code after you sane, I'd also suggest different id values for the version frame and the version input inside it.