Question

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>
Was it helpful?

Solution

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

Demonstration

Modifying the prototype of objects you don't own is generally frowned upon but this change is rather innocuous and natural.

OTHER TIPS

Usually if many elements need the same event listener you can add the event listener to the container and filter out what element you would like to take action upon:

document.addEventListener("click",function(e){
  if(e.target,e.target.tagName.toLowerCase()==="a"){
    e.preventDefault();
  }
});

If you were to add extra anchor tags through script they will trigger the preventDefault too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top