Disco
Disco

Reputation: 4386

get identifier of link given the class jquery

i have this piece of html

<li><a href="#" id="9000" class="yes vpslink"><img src="x.gif" /></a></li>
<li><a href="#" id="9001" class="no vpslink"><img src="x.gif" /></a></li>


$('.vpslink').click(function(e) {
   var id='i dont know dude'; 
   alert('you clicked on id'+id);
}); 

How do I find the id of this class, link ?

Upvotes: 1

Views: 1798

Answers (3)

Headshota
Headshota

Reputation: 21449

$('.vpslink').click(function(e) {
   var id= $(this).attr('id'); 
   alert('you clicked on id ' + id);
}); 

Upvotes: 2

user113716
user113716

Reputation: 322502

$('.vpslink').click(function(e) {

      // Quick way to get the ID
   var id = this.id;

      // Replace the SRC of the sibling <img> 
   $(this).siblings('img').attr('src', function(i,src) {
        return (src == 'x.gif') ? 'y.gif' : 'x.gif';
   });

});

The fastest way to get the ID of the element is to access its DOM property directly with this.id.

You can use .siblings() to get the sibling <img> and .attr() to update the source. The .attr() method can take a function as a parameter that returns the value to set.

Upvotes: 1

carpie
carpie

Reputation: 301

Inside the click handler:

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

Upvotes: 2

Related Questions