Get clicked link id

In the code below and the demo here http://jsfiddle.net/jasondavis/vp2YN/3/ you can see that I need to get the id attribute of the clicked element and assign its variable in Javascript.

Currently, the code returns the name of the identifier of the first element, regardless of which element the button is clicked on.

In Javascript, you can see this line is commented out ...

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

Please help me get the id of the 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/

+4
source share
1 answer

You must reference the one you clicked with the jQuery wrapper!

Do you want to use

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

To get the id (without going through the DOM for no reason), you'd better just call the id object.

 this.id; 

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

 jQuery('.insertcolumn').click(function(){ var clickedID = $(this).attr('id'); alert(clickedID); });​ 
+9
source

Source: https://habr.com/ru/post/1434403/


All Articles