SkyeBoniwell
SkyeBoniwell

Reputation: 7092

get the ID of a link when clicked

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

Answers (3)

j08691
j08691

Reputation: 207881

Change:

console.log('clicked: ' + a.id);

to:

console.log('clicked: ' + this.id);

jsFiddle example

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

owsata
owsata

Reputation: 1225

Use

$("#webLinks a").on('click', function () {
       $(this).attr('id');
});

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You should use this.id instead of a.id

DEMO

Upvotes: 3

Related Questions