when i use the .preventDefault on a link it still goes to the link - also is this even doable with JS or is it a jquery only method?
var avoidlink = getElementsByTagName("a");
avoidlink.addEventListner("click",function(evt){
evt.preventDefault();
},false);
<a href="http://www.google.com">Click here</a>
Three problems :
getElementsByTagName
must be called on the document or on an elementgetElementsByTagName
, you must iterate over the elements it contains :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.