0

I have a C++ (.cpp) file whose contents I would like formatted on my webpage. I have it stored locally; call it myFile.cpp. The process I need is:

  • Get contents of myFile.cpp stored as a JavaScript string codeText
  • Replace all of codeText's < characters with &lt; and all > characters with &gtl;
  • Made codeText the inner HTML of <pre class="prettyprint" id="blah"> (Google's code pretifier will applied inside there)

So here's my horrible attempt that isn't working:

        var codeText;
        var codeFile = new XMLHttpRequest();
        codeFile.open("GET", "myFile.cpp", false);
        codeFile.onreadystatechange = function ()
        {
          if(codeFile.readyState === 4)
          {
            console.log(codeFile.status);
            if(codeFile.status === 200 || codeFile.status == 0)
            {
              codeText = codeFile.responseText;
            }
          }
        }
        codeFile.send(null);
    codeText = AB_Escape(codeText);
    document.getElementById("blah").innerHTML = codeText;

where

function AB_Escape(txt)
{
    txt.replace("<","&lt;");
    txt.replace(">","&gt;");
    return txt;
}

This isn't working: my console reads Uncaught TypeError: Cannot set property 'innerHTML' of null

Hopefully that gives you an idea of what I'm trying to do. How can I do it correctly?

  • No, simply [don't use `innerHTML` but the DOM](http://stackoverflow.com/a/13122927/1048572)! No need for manually escaping anything then. – Bergi Jun 03 '14 at 23:17
  • possible duplicate of both [How to return the response from an AJAX call?](http://stackoverflow.com/q/14220321/1048572) (don't use SJAX!) and [Why does jQuery or a DOM method such as `getElementById` not find the element?](http://stackoverflow.com/q/14028959/1048572) – Bergi Jun 03 '14 at 23:18

2 Answers2

0

Move:

codeText = AB_Escape(codeText);
document.getElementById("blah").innerHTML = codeText;

To the if-loop where you check whether status equals 200:

if(codeFile.status === 200 || codeFile.status == 0)
{
    codeText = codeFile.responseText;
    codeText = AB_Escape(codeText);
    document.getElementById("blah").innerHTML = codeText;
}

You have to process codeText after the code file is received. The file is not received yet when you call the send command.

Tomasz Nguyen
  • 2,561
  • 22
  • 25
0

Your script is executed before the element can be reached,
on the right place and/or at right time it works fine http://www.freakstyle.it/cpp/
so : put the script at bottom OR do it at Dom loaded

Community
  • 1
  • 1
fedeghe
  • 1,243
  • 13
  • 22