webGuy
webGuy

Reputation: 163

How to detect current element in jQuery?

I want to add an attribute data-pic via jquery to multiple img tags:

$('#description img').attr('data-pic', $(this).attr('src') )

but, $(this).attr('src') won't work. What I need is the src of the current element (img) I am working with.

Upvotes: 0

Views: 91

Answers (3)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

You need to use a callback function to use the contextual this keyword.

$('#description img').attr('data-pic', function () {
  return $(this).attr('src');
} );

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

I add the attribute data-pic via jquery to images (more than 1):

You need to use a loop on each image.

$('#description img').each(function(){
   $(this).attr('data-pic', $(this).attr('src') )
})

Upvotes: 4

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you can use a direct loop with each(). This will give you the this reference within the handler function:

$('#description img').each(function() {
  $(this).attr('data-pic', $(this).attr('src'));
});

Alternatively you can provide a function to attr() which will work on each element instance:

$('#description img').attr('data-pic', function() {
  return $(this).attr('src');
});

Upvotes: 0

Related Questions