html - Click a link with href attribute and execute the Javascript function -


my script contains link a element href attribute of "#login" below.

<a href="#login">login</a> 

i want javascript function detect "href" element in link , execute. how can this? javascript function is

window.onload = function() {     document.getelementsbytagname("a[href=#login]").onclick = function(e) {         e.preventdefault();         alert("working");     } } 

why have seen no queryselector love in these answers?

if want use css selector grab link, nothing stopping you:

window.onload = function() {    document.queryselector("a[href='#login']").onclick = function(e) {      e.preventdefault();      alert("working");    }  }
<a href="#login">login</a>

edit: saw in answer believe there may multiple links on page match selector, in case you'll need loop through them:

window.onload = function() {    var links = document.queryselectorall("a[href='#login']"),        //always create anonymous functions outside of loop :)        click = function(e) {          e.preventdefault();          alert("working");        }, i;    (i = 0; < links.length; i++) {      links[i].onclick = click;    }  }
<a href="#login">login</a>  <a href="#login">login</a>


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -