document.createElement and checkboxes

June 03, 2008 @ 12:03 pm

1 Comment

I ran into a problem in building the web interface for SnapTest today, where I couldn't seem to get a checkbox to show up as checked in IE. The original code looked something like

And no matter how many times I tried, IE (6 specifically) refused to check the checkbox. It turns out IE want your checkboxes made in a Mozilla-incompatible way. Specifically, IE lets you call document.createElement using an entire HTML tag, which will result in a node you can perform operations on.

I almost fell back on the conditional comment browser sniff from Dean Edwards, but ended up with something I felt was much better. Everything beaten into your head about JavaScript says that feature detection is the better alternative to browser sniffing, so why not treat IE's rendering of an HTML tag as a "feature" instead of a bug.

A couple minutes later, I had a working solution.

I guess I had never really thought of IE's bugs as features before; changing the way you can code for IE's differences from other browsers.

In response to "document.createElement and checkboxes":

  1. June 13, 2008 at 11:29 am

    I didn’t believe it when I read it...but I just tried it and you’re right!  It seems the problem is creating that “state” before it is added to the document.  After some experimenting I noticed that you can set the “checked” state after it has been added to the document.

    // Script start
    var checkbox = document.createElement("input");
    checkbox.type = “checkbox”;

    var div = document.getElementById("testContainer");
    div.appendChild(checkbox);

    checkbox.checked = true;
    // Script end

    Still pretty silly of IE6.

Leave a Reply:

Commenting is not available in this section entry.