Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  96] [ 2]  / answers: 1 / hits: 107267  / 13 Years ago, mon, september 26, 2011, 12:00:00

So maybe I'm just not looking in the right places but I can't find a good explanation of how to do the equivalent of jQuery's



$('a').click(function(){
// code here
});


in plain old JavaScript?



Basically I want to run a function every time an a tag is clicked but I don't have the ability to load jQuery into the page to do it in the way above so I need to know how to do it using plain JavaScript.


More From » jquery

 Answers
18

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;
};
}

[#89920] Saturday, September 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
xiomara

Total Points: 378
Total Questions: 90
Total Answers: 104

Location: Guernsey
Member since Thu, Oct 7, 2021
3 Years ago
;