Reputation: 7092
I'm trying to get the ID of a link when clicked. I don't want the link to go anywhere, I just want the ID.
So far, the code does not write anything to the console. I'm not sure what I'm doing wrong.
Here is my code:
$("#webLinks a").on('click', function () {
console.log('clicked: ' + a.id);
});
<div id="webLinks">
<div class="linkRows">
<div name="link1">
<a id="webLink1" href="#" name="www.google.com">Google</a>
</div>
</div>
</div>
Thanks
Upvotes: 0
Views: 70
Reputation: 207881
Change:
console.log('clicked: ' + a.id);
to:
console.log('clicked: ' + this.id);
this
refers to the element receiving the click. In your original code, a
doesn't refer to the anchor (or anything) so it's undefined.
Also, make sure your code is being run after the elements exist on the page or from within a document ready call:
$( document ).ready(function() {
// Your code here
});
Upvotes: 8
Reputation: 1225
Use
$("#webLinks a").on('click', function () {
$(this).attr('id');
});
Upvotes: 0