0

My script contains a link a element with href attribute of "#login" as below.

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

I want to my Javascript function detect the "href" element in the link and execute. How can I do this? My Javascript function is

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

3 Answers 3

2

Why have I seen no querySelector love in these answers?

If you want to use that CSS selector to grab your link, nothing is stopping you:

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

EDIT: I saw in another answer that you believe there may be multiple links on a page that match that selector, in which case you'll need to loop through them:

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

<a href="#login" onclick="getValue()">Login</a>

function getValue()
{
    alert("working");
    e.preventDefault();  
}

FIDDLE

Comments

0

Your getElementsByTagName is treating it like a jquery selector, which it is not designed to do.

It would be much simpler to give the tag an id and use getElementById:

window.onload = function() {
    document.getElementById("loginLink").onclick = function(e) {
        e.preventDefault();
        alert("working");
    }
}
<a href="#login" id="loginLink">Login</a>

If for whatever reason you cannot change the html and you want to do it this way you would need to get all a tags then loop through each one to test the href attribute. Note you need to use a.getAttribute("href") to get "#login", rather than just a.href which oftens give you an full URL:

window.onload = function() {
  var aTags = document.getElementsByTagName("a");
  for(var i = 0; i < aTags.length; i++) {
    var a = aTags[i];
    if(a.getAttribute("href") == "#login") {
      a.onclick = function(e) {
        e.preventDefault();
        alert("working");
      }
    }
  }
}
<a href="#login">Login</a>
<a href="#test">Test</a>
<a href="#login">Login Again</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.