Java

IE/JavaScript Insanity – appendChild() changes the appended object!

I’ve been hacking around with Javascript a good bit lately. Since we’re writing internal apps at the moment, we can more or less dictate what browsers to use, or at least we can insist that we will NOT support Netscape 4 and IE
function addRow( rowName, myValue ) {
var newItem = document.getElementById(“blankItem”).cloneNode(true);
var group = newItem.getElementsByTagName(“span”).item(0);
group.appendChild(document.createTextNode(rowName));
var checkboxes = newItem.getElementsByTagName(“input”);
checkboxes.item(0).checked = myValue;
alert(newItem.getElementsByTagName(“input”).item(0).checked);
itemList.appendChild(newItem);
alert(newItem.getElementsByTagName(“input”).item(0).checked);
}

blankItem is defined elsewhere in the page as:

  <tr id="blankItem">
    <td><span></span></td>
    <td><input type="checkbox" name="test"></td>
  </tr>

The intent here is to add a new row to a table based on user input from a form. It works great in Mozilla/Firefox. But clearly someone working on Internet Explorer was smoking crack the day they wrote the code to support this (version 6.0.2800.1106). Changing the span to contain the user text works fine. But interesting things happen when you change the value of the checkbox. The default value is true. If you pass false into the function, the first debug statement shows false, but the second shows true. The appendChild() statement actually changes the element being appended! How or why this happens, I can’t say, but it took me a couple of hours of frustration to get past it. One more reason I wish people would abandon using Internet Explorer.

Advertisements