String contains an invalid character

Wow, it’s been over a month since I posted anything on here. I must be slacking big time! Well, here’s a goody I found recently…

I was playing around with a third party JavaScript library the other day. Not really using it for anything, just wanted to see how it worked. Anyway, the first time I fired up the demo that came with it, it doesn’t work and this shows up in firebug:

String contains an invalid character

Inspecting a bit further I find a bunch of gems like this:

var div = document.createElement("<div name='hello'>");

Wait, what? WTF is that? That’s not how createElement is used! It seems yet again, Internet Explorer deviates drastically from the standard and lets you do ugly nasty things like that. So the code above only works in Internet Explorer. It is broken everywhere else. As an example, the following is IE only:

<html>
  <head>
    <script type="text/javascript">;
    function load()
    {
      var body = document.getElementsByTagName("body")[0];
      var div = document.createElement("<div name='hello'>");
      div.innerHTML = "Hello, world!";
      body.appendChild(div);
    }
    window.onload = load;
    </script>
  </head>
  <body>
  </body>
</html>

This is also IE only:

<html>
  <head>
    <script type="text/javascript">
    function load()
    {
      var body = document.getElementsByTagName("body")[0];
      var div = document.createElement("<div>");
      div.setAttribute("name", "hello");
      div.innerHTML = "Hello, world!";
      body.appendChild(div);
    }
    window.onload = load;
    </script>
  </head>
  <body>
  </body>
</html>

This is the correct way to do it!

<html>
  <head>
    <script type="text/javascript">
    function load()
    {
      var body = document.getElementsByTagName("body")[0];
      var div = document.createElement("div");
      div.setAttribute("name", "hello");
      div.innerHTML = "Hello, world!";
      body.appendChild(div);
    }
    window.onload = load;
    </script>
  </head>
  <body>
  </body>
</html>

Note the use of innerHTML. This was originally another Microsoft-ism. However, it’s been adopted by all major browsers and is now officially in HTML5 so I don’t feel quite so dirty for using it!

Related Posts

Leave a Reply