Passing data to a jQuery click() function Passing data to a jQuery click() function ajax ajax

Passing data to a jQuery click() function


If you insist on using old-school HTML 4.01 or XHTML:

$('.removeAction').click(function() { // Don’t do anything crazy like `$(this).attr('id')`. // You can get the `id` attribute value by simply accessing the property: this.id; // If you’re prefixing it with 'my' to validate as HTML 4.01, you can get just the ID like this: this.id.replace('my', '');});

By the way, in HTML5, the id attribute can start with a number or even be a number.

Then again, if you’re using HTML5 anyway, you’re probably better off using custom data attributes, like so:

<span class="action removeAction" data-id="1">Remove</span>


$(this) within your click function represents the clicked element

$(".removeAction").click(function() {    //AJAX here that needs to know the ID    alert($(this).attr('id'));           }


The following code will get you the ID of the clicked span. Using the ID isn't perfect, but it will work.

$(".removeAction").click(function() {  alert($(this).attr("id"));});