getElementById Helper

From GreaseSpot
Jump to: navigation, search


Many libraries provide a $() function to make it easier to reference elements by their ID. It's easy to add your own function for this sort of behavior.

function $() {
  if (arguments.length==1) {
    return document.getElementById(arguments[0]);
  }

  var result=[], i=0, el;
  while(el=document.getElementById(arguments[i++])) {
    result.push(el);
  }

  return result;
}

And it can be used easily:

$("header").innerHTML = "Lorem ipsum, solor dit amet";
$("header", "footer", "content").forEach(function(element) {
  element.parentNode.removeChild(element);
});
Personal tools