JavaScript Helper Functions

When you cannot or don't want to use a JavaScript toolkit like jQuery these functions may come in handy. However, they do not globally work on IE. With IE you will need to supply the object that you want it set on.

var addEvent = function(obj, evType, fn) {
  if(obj.addEventListener) {
    obj.addEventListener(evType, fn, false);
    return true;
  } else if(obj.attachEvent) {
    var r = obj.attachEvent("on" + evType, fn);
    return r;
  } else {
    return false;
  }
}

var insertAfter = function(newNode, refNode) {
  var result = null;

  if(refNode.nextSibling) {
    result = this.insertBefore(newNode, refNode.nextSibling);
  } else {
    result = this.appendChild(newNode);
  }

  return result;
}

var getElementByClass = function(className, count) {
  var result = null;

  for(var i = 0; i < this.childNodes.length; i++) {
    var classCount = 0;

    if(this.childNodes[i].className == className) {
      if(classCount == count) {
        result = this.childNodes[i];
        break;
      }

      classCount++
    }
  }

  return result;
}

var extendNode = function() {
  // Most browsers have a Node object.
  if(window.Node) {
    Node.prototype.insertAfter = insertAfter;
    Node.prototype.getElementByClass = getElementByClass;
  } else {  // IE doesn't, so we have to set it to the object we need it on.
    var container = document.getElementById("The Object You Need It Set On");
    container.insertAfter = insertAfter;
    container.getElementByClass = getElementByClass;
  }
}

addEvent(window, "load", extendNode);