html - Get reference to anchor's dom element from javascript - Stack Overflow

If I have a some javascript in an anchor's href attribute:<a href="javascript:alert('

If I have a some javascript in an anchor's href attribute:

<a href="javascript:alert('hello!')">

Is there a way I can get a reference to the DOM element that was clicked when the script executes? I mean, I know I could do

<a href="javascript:alert('hello from '+document.getElementById('thisAnchor'))" id="thisAnchor">

But I was hoping for something more like

<a href="javascript:alert('hello from '+target)">

If I have a some javascript in an anchor's href attribute:

<a href="javascript:alert('hello!')">

Is there a way I can get a reference to the DOM element that was clicked when the script executes? I mean, I know I could do

<a href="javascript:alert('hello from '+document.getElementById('thisAnchor'))" id="thisAnchor">

But I was hoping for something more like

<a href="javascript:alert('hello from '+target)">
Share Improve this question asked Sep 22, 2010 at 19:58 rampionrampion 89.2k49 gold badges206 silver badges320 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Something like this?

Example: http://jsfiddle/TTzDb/

<a href="#" onclick="alert('hello from '+this.innerHTML)">me</a>​​​​​​​​​​​​​​

Using onclick, this will refer to the element that received the event.

Move the JavaScript to the onclick="yourJavaScriptHere" attribute. Then you can use the 'this' keyword to reference your anchor. So

<a href="#" onclick="alert('hello from '+this)">some text</a>

Although, that isn't very meaning. Additionally, it is a better practice to separate your JavaScript from your HTML to build a more maintainable website.

Yes, and the answer is this which refers to current DOM element:

<a href="javascript:alert('Hello from ' + this.tagName);">Click me</a>

EDIT:

Of course as bobince mentioned (see ments) that won't work as excepted. The correct form is:

<a href="..." onclick="alert('Hello from ' + this.tagName);">Click me</a>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745542575a4632194.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信