pure javascript equivalent of jquery click()?

hoball picture hoball · Jul 22, 2009 · Viewed 15.9k times · Source

I am building a small app which captures mouse clicks. I wrote the prototype in jquery but, since it is a small app focusing on speed, embedding jquery to use just one function would be an overkill.

I tried to adapt this example from JavascriptKit:

document.getElementById("alphanumeric").onkeypress=function(e){  
    //blah..blah..blah..  
}

but it didn't work when I tried

document.getElementsByTagName("x").onclick

What am I doing wrong?

Answer

DLS picture DLS · Jul 22, 2009

Say you have a list of p tags you would like to capture the click for the p tag:

var p = document.getElementsByTagName("p"); 
for(var i=0; i<p.length; i++){ 
 p[i].onclick = function(){ 
   alert("p is clicked and the id is " + this.id); 
 } 
}

Check out an example here for more clarity: http://jsbin.com/onaci/