-2

Good day! For example I have this code:

<a href="link" onclick="myfunc()">Secret link</a>

How can I transmit its values such as: href, and name to the onclick event without defining it in the myfunc('link', 'name') explicitly? Maybe, there is something like:

<a href="link" onclick="myfunc(this)">Secret link</a>

P.S. I do not use JQuery

3 Answers3

2

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
2

How can I transmit its values such as: href, and name to the onclick event without defining it in the myfunc('link', 'name') explicitly?

You can get it from this itself using getAttribute and innerText

function myfunc( thisObj )
{
   var link = thisObj.getAttribute( "href" );
   var name = thisObj.innerText;
}

and pass this with onclick

<a href="link" onclick="myfunc(this)">Secret link</a>

Also, try doing it without inline event

document.querySelector( "a" ).addEventListener( "click", function( event ){
   event.preventDefault(); //to prevent default action of link click
   var link = this.getAttribute( "href" );
   var name = this.innerText;
});
gurvinder372
  • 61,170
  • 7
  • 61
  • 75
0

You can use getAttribute

getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string)

function myfunc(elem) {
  console.log(elem.getAttribute('id'))
}
<a href="#" id="click" onclick="myfunc(this)">Secret link</a>
Bhuwan
  • 15,392
  • 4
  • 26
  • 50