August 19, 2008 | Category: Uncategorized

Fixing a Gap in Javascript

An interesting problem: a bunch of Struts Nested tags generate HTML. Separately, we write some Javascript that makes use of getElementById() to find some of the generated elements. This works in Internet Explorer, but fails miserably in FireFox. Why?

Well, it turns out that Struts Nested tags generate elements that have a name attribute but not an id. Separately, IE actually does the wrong thing with getElementById(): if a search by id fails, it will try to match by name; that’s fundamentally broken. It’d be fine if a bunch of libraries and other functions didn’t prefer the use of ids, and if other browsers did the same thing. They don’t and we’re stuck with the mess. Let’s clean it up.

The right thing to do would be to cripple the IE version into the correct behaviour. Now everyone agrees on what should happen.

Let’s assume, though, that this isn’t possible, that there’s a large dependency on this behaviour that cannot be changed for whatever reason: no access to the JS, unwieldy codebase that we don’t have time to fix straight away (bad!), or something else. It’s not really that important. If you need to go for the wrong solution, here’s how:

`

document.nativeGetById = document.getElementById;
document.getElementById = function(id){
  var el = document.nativeGetById(id);
  if(el == null){
    el = document.getElementsByName(id)[0];
    if(el != null){el.id=id;}
  }
  return el;
}

` That’ll work and it’ll even make sure subsequent calls use the native version of the function for extra speed. Now, there are a couple of small issues with this function and some pretty obvious optimisations, but I’ll leave that as an exercise for the reader.