Abbreviating getElementById

By John Slater

All JavaScript toolkits have a way of abbreviating document.getElementById. If you do this abbreviation yourself, using the following fashion:

var dd;
function onLoad {
  dd=document.getElementById;
  dd("mybutton").value="Press Me"; // FF throws an exception here
}

Firefox will throw an exception and give the message:

"Illegal operation on WrappedNative prototype object" 
nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO).

The problem is that getElementById is a method of document while dd is a function, not a method. In IE, function calls are associated with a global object that is the window or document; and everything still works. But we run out of luck when FF is the browser.

Use a function factory routine which returns a wrapper that keeps the method associated w/it's object, like this:

function attachMethod(obj,method) {
  return (typeof(method)=="string") ? function() { return obj[method].apply(obj,arguments); }
                                    : function() { return      method.apply(obj,arguments); };
}

Code will need to look like this:

var dd;
function onLoad {
  dd1 = attachMethod(document,"getElementById"); 
  dd1("mybutton1").value = "Press Me1";
// or
  dd2 = attachMethod(document,document.getElementById);  
  dd2("mybutton2").value = "Press Me2";
}

This discussion was inspired by michele cicciot