Maybe, there is something like
<a href="link" onclick="myfunc(this)">Secret link</a>
Yes, exactly link that. Then in myfunc
, you use the parameter's properties and/or attributes:
function myfunc(link) {
console.log(link.href);
}
The properties of an HTMLAnchorElement
are listed in the spec. If you include other information (such as data-*
attributes) on the element (or you want the raw href
, not the resolved one), get them via the getAttribute
method (DOM4, MDN).
Since it's a link, though, if you're responding to a click on it you may also want to prevent the link's default action (following the link). To do that, you'd add return
to the onclick
and also return false;
from the handler. Live example:
function myfunc(link) {
console.log("href property: " + link.href);
console.log("href attribute: " + link.getAttribute("href"));
return false;
}
<a href="link" onclick="return myfunc(this)">Secret link</a>
Rather than using onxyz
-attribute-style event handlers, though, I do recommend reading up on addEventListener
and event delegation.