Reputation: 63727
A <img />
element has a data-id
attribute that I want to retrieve using jQuery. I believe the .data()
function can do this.
$('.photo').get(0).data('id')
Problem: When I tried using .data('id')
to retrieve the attribute, I get the error:
Uncaught TypeError: Object #<HTMLImageElement> has no method 'data'
Where did I go wrong?
jsfiddle: http://jsfiddle.net/KLG3R/
Upvotes: 1
Views: 1264
Reputation: 25
data()
method, while DOM object like your xx..get(0)
has no method data();
data()
method, you must ensure the object is jQuery object.Upvotes: 0
Reputation: 5050
Your using jQuery .get()
you need to use .eq()
in this case. Also your using .data()
which is used to store data on the dom. You need to be using .attr()
which gives you access to the attributes of the element.
$(function () {
var photos = $('.photo');
$('#result').html(photos.eq(0).attr('data-id'));
});
This should be working for you now: http://jsfiddle.net/KLG3R/4/
Upvotes: 0
Reputation: 3281
like others said, your problem is the .get(0)
which returns the HTML element itself, rather than a jquery object. To get a certain element, you use the :eq
pseudo selector like:
http://jsfiddle.net/gunderson/KLG3R/2/
$('#result').html( $('.photo:eq(0)').data('id') );
Upvotes: 5
Reputation: 398
use .attr() function. Like
$('#result').html( $('.photo').attr('data-id') );
Upvotes: 0
Reputation: 160963
$('.photo').get(0)
will return the HTMLImageElement
, not the jQuery object, so it doesn't have a method .data
.
You should just do with: $('.photo').data('id')
Upvotes: 0
Reputation: 2653
You need to use data to a jquery object and get(0) will return the element.
$('#result').html( $('.photo').data('id') );
Check the below fiddle
Upvotes: 0