Three problems :
getElementsByTagName
must be called on the document or on an element- You can't add an event listener directly on the node list returned by
getElementsByTagName
, you must iterate over the elements it contains : - you have a typo in
addEventListener
Here's a fixed code :
var avoidlink = document.getElementsByTagName("a");
for (var i=0; i<avoidlink.length; i++) {
avoidlink[i].addEventListener("click",function(evt){
evt.preventDefault();
},false);
}
If you want to be able to attach an event listener to a node list, you may enrich NodeList.prototype
:
NodeList.prototype.addEventListener = function(){
for (var i=0; i<this.length; i++) {
Element.prototype.addEventListener.apply(this[i] , arguments);
}
}
Modifying the prototype of objects you don't own is generally frowned upon but this change is rather innocuous and natural.