Search code examples
javascripthtmlpreventdefault

JS .preventDefault not working


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>

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.