BlackFire27
BlackFire27

Reputation: 1550

Cant get an attribute of an element with jquery

I have got this html:

<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">

I am trying to get this:

$('body').on('click','.hostPic',function(){ 
    console.log($(this).attr('data-name'));
});

Whenever the picture is pressed, I want to gets its data-name attribute, but it doesnt work.. I get undefined reported when I try to retrieve the attribute. Any reason why?

Upvotes: 0

Views: 68

Answers (4)

Onur Topal
Onur Topal

Reputation: 3061

The following code worked for me, maybe you are attaching the events wrong object, you can understand that by debugging the this object instead of data-name.

And another thing is if you are going to use .data just for read string you should use .attr as the .data caches and tries to convert the value its appropriate type like number or JSON it is a heavier process than .attr.

<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">​

​$("img")​.click(function () { alert($(this).attr("data-name")); });​

Upvotes: 0

Anujith
Anujith

Reputation: 9370

$('.hostPic').click(function() {
  console.log($(this).data('name'));
}

Upvotes: 1

drmonkeyninja
drmonkeyninja

Reputation: 8540

Make sure your image has the class 'hostPic' and then do the following in your jQuery:-

$('.hostPic').on('click', function() {
  console.log($(this).data('name'));
}

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

Add the hostPic class to that image.

Additionally, you can just use .data('name'), but it doesn't actually make a difference. Older browser may have trouble with .data, but it's never been a problem for me.

Upvotes: 4

Related Questions