Reputation: 15
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");
}
}
Upvotes: 0
Views: 2593
Reputation: 5607
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>
Upvotes: 2
Reputation: 16609
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>
Upvotes: 0
Reputation: 2275
Try this:
<a href="#login" onclick="getValue()">Login</a>
function getValue()
{
alert("working");
e.preventDefault();
}
Upvotes: 0