Archive

Posts Tagged ‘getelementsbyid’

Javascript Tip: getElementsByID

March 17th, 2008

Browsers do a lousy job of providing an interface to the HTML document. The DOM is supposed to be that interface but it is horribly slow, and clunky. Traversing the DOM tree extensively is one of the sure-fire way to slow down your site. In an effort to help out Javascript coders, the DOM does have functions like getElementsByTagName, getElementsByClassName and getElementsByName, but they do not all work across all browsers. This why you should create a function called getElementsByID:

var groupCache = {};
function getElementsById(id){
  if(!groupCache[id]){
    groupCache[id] = [];
  }
  var nodes = groupCache[id];
  for(var x=0; x<nodes .length; x++){
    if(nodes[x].id != ""){
      nodes.splice(x, 1);
      x--;
    }
  }
  var tmpNode = document.getElementById(id);
  while(tmpNode){
    nodes.push(tmpNode);
    tmpNode.id = "";
    tmpNode = document.getElementById(id);
  }
  return nodes;
}

Now whenever you want a collection of DOM objects, just give all of them the same id and call this function to grab an array of the objects you want. This is not the most ideal way and its actually a pretty big hack. But sometimes, speed is more important than form.

programming , , , , , , , , , , ,