Vanilla JavaScript version of jQuery .click

Working Example: http://jsfiddle.net/6ZNws/

Html

<a href="something">CLick Here</a>
<a href="something">CLick Here</a>
<a href="something">CLick Here</a>

Javascript:

var anchors = document.getElementsByTagName('a');
for(var z = 0; z < anchors.length; z++) {
    var elem = anchors[z];   
    elem.onclick = function() {
        alert("hello");
        return false;
    };
}

Try the following

var clickHandler = function() { 
  // Your click handler
};

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
  var current = anchors[i];
  current.addEventListener('click', clickHandler, false);
}

Note: As Ӫ_._Ӫ pointed out this will not work on IE8 and lower as it doesn't support addEventListener.

On IE8 you could use the following to subscribe to onclick. It's not a perfect substitute as it requires everyone to be cooperative but it may be able to help you out

var subscribeToOnClick = function(element) {
  if (element.onclick === undefined) {
    element.onclick = clickHandler;
  } else {
    var saved = element.onclick;
    element.onclick = function() {
      saved.apply(this, arguments);
      clickHandler.apply(this, arguments);
    }
  }
}

for (var i = 0; i < anchors.length; i++) {
  var current = anchors[i];
  subscribeToOnClick(current);
}

element.addEventListener('click', function() { ... }, false);

You have to locate the elements and make a loop to hook up each one.


document.getElementById('elementID').onclick = function(){
      //click me function!
}