IE vs FireFox: Using JavaScript to modify attributes
Saturday, April 19th, 2008I was working on an interesting little project involving the Google Website Optimizer and ran into this little gem.
The task was to use JavaScript to rewrite a page that was formatted using tables and was sometimes missing a row that spanned the whole table. Now I have to admit that I am not a JS or DOM pro, But I’ve picked up though some experience through this and a couple other tasks. So here is the base HTML:
<table id="table" border=1> <tr id="leftcol"> <td>foo</td> <td>bar</td> </tr> </table>
The goal is to make the DOM look like this:
<table border=1> <tr> <td colspan=2>colspan test</td> </tr> <tr> <td id="leftcol">foo</td> <td id="rightcol">bar</td> </tr> </table>
So the JavaScript is supposed to do that looks something like this:
<script>
var element = document.getElementById("rightcol");
var newrow = element.parentNode.parentNode.insertRow(0);
var newcell = newrow.insertCell(0);
newcell.innerHTML("colspan test");
newcell.setAttribute("colspan", "2");
</script>
I was developing it in FireFox thanks to the FABULOUS tool FireBug which lets me test the JS in a command line environment before actually storing it in a file but of course I had to test it in IE as well. The raw HTML file appears the same way (and correctly) in both browsers.
But when I add the JavaScript, I get differences when I check them in the browsers.
In IE, the colspan attribute didn’t seem to have an effect. Hmm, okay I will check with the IE Developer Toolbar which is no FireBug, but at least lets you see how IE is interpreting the code.

Okay, so the colspan attribute is set. So why isn’t it being applied??? Try resetting the attribute in the Developer Toolbar to “2″ by clicking on the value and then hitting <enter> (choose “This cell only”).
Hmm, the result looks good, but there are TWO attributes, “colspan” and “colSpan”. So going back to the original HTML code, and looking at that in the Developers Toolbar shows that IE has converted the attribute to the appropriate case from the original HTML:
But that it doesn’t do that when the attribute is set through JavaScript.
I know you can use the JS object property (td.colSpan) to set the attribute as well which is a function, so well documented to be case sensitive, but my understanding has always been that HTML elements and attributes are not. Why does IE follow that in the HTML, but not in the JS functions that modify it? I don’t know. It seems silly to me.
John




