Another Reason Why innerHTML Sucks
So everyone loves superfluous JavaScript right? Especially the kind that makes good sites suck a lot. Currently at the studio, I’m working on a project where the client wishes to have a text input field pop up when a user clicks on a cell in a table so they can edit the contents within. If you’ve ever edited an appointment using Google Calendar, you’ll know exactly what I’m talking about.So I had an impure thought… I figured that although innerHTML isn’t part of the W3 DOM, it is still supported by all A-Grade browsers. Since I did a great job of convincing myself that it was OK, I decided to write a simple function that makes this a breeze.
function mkInput(e, name, value) { if(e.innerHTML.indexOf('input') == -1) { e.innerHTML = '<input type="text" name="' + name + '" value="' + value + '" />'; return; } else { return; } }
This could easily be tied into the onClick event of a table cell. To put it rather obtrusively:
<td onclick="mkInput(this, 'foo', this.innerHTML)">Pink Flamingo</td>
See the problem? Neither did I. The if(e.innerHTML.indexOf(’input’) == -1) simply checks to see if the word “input” is found at any place within the contents of the table cell. If not, stuff the innerHTML property of the cell to contain the newly created input. The purpose of the conditional is simply to avoid adding, and re-adding the the input field every time a user clicks on it (say, to edit the value or something silly like that).
The problem lies here. The function’s execution depends solely on the string in contained in the innerHTML property. As I soon found out (and should have expected), Gecko-based browsers work just fine whereas IE doesn’t. The reason for this can be seen by adding a quick alert as the first line within the function’s definition.
alert(e.innerHTML);</li>
If you were to open your handy-dandy Gecko derived web browser you see:
<input class="td" type="text" name="foo" value="Pink Flamingo" />
As expected, of course. Unfortunately, the same is not so for Internet Explorer 6.
<INPUT class=td type=text name=foo value="Pink Flamingo" />
So what about an actual solution? Well, for starters, trustworthy pattern matching generally only possible via regular expressions. But even with a solid regex, would that still be the correct way to accomplish this problem? I say not. As much of a royal pain in the ass that using the DOM can be, it’s worth it in the long run.
Comments are closed. Sorry.