JasonDavis
JasonDavis

Reputation: 48933

Get ID of a Clicked Link

In the code below and demo here http://jsfiddle.net/jasondavis/vp2YN/3/ you can see I need to get the ID attribute of a clicked item and assign it to a variable in Javascript.

Right now the code returns the ID name of the first item, regardless of which item is clicked on.

In the Javascript you can see I have this line commented out...

var clickedID = this.attr("id"); when I use that line, I get an error saying: Object has no method 'attr'

Please help me get the ID name of the clicked link and assign it to a variable

HTML

<a href="#" style="display:block" class="button insertcolumn" id="one_half">2 Columns</a>

<a href="#" style="display:block" class="button insertcolumn" id="one_third">3 Columns</a>

<a href="#" style="display:block" class="button insertcolumn" id="one_fourth">4 Columns</a>​

Javascript/jQuery

jQuery('.insertcolumn').click(function(){

    var clickedID = jQuery('.insertcolumn').attr("id");
    //var clickedID = this.attr("id");

    alert(clickedID);

});​

Demo http://jsfiddle.net/jasondavis/vp2YN/3/

Upvotes: 5

Views: 11152

Answers (1)

Zevi Sternlicht
Zevi Sternlicht

Reputation: 5399

You have to reference the one you clicked with the jQuery wrapper!

You want to use

$(this).attr('id');

To get the id (without traversing the DOM for no reason) you would be better off to just call the object id.

this.id; 

But to access the property regardless of the type of attribute and depending on the name of the attribute use the following code.

jQuery('.insertcolumn').click(function(){

    var clickedID = $(this).attr('id');


    alert(clickedID);

});​

Upvotes: 9

Related Questions