1

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/

1
  • $('#result').html($('.photo').data('id')); works for me. Commented Dec 17, 2012 at 3:22

6 Answers 6

5

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') );
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, you could use first() to get the first element from your set of elements. $('.photo').first().data('id').
0

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

http://jsfiddle.net/KLG3R/1/

Comments

0

$('.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')

Comments

0

use .attr() function. Like

$('#result').html( $('.photo').attr('data-id') );

Comments

0

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/

Comments

0
  1. There are two types of an element. That is DOM object and jQuery object;
  2. jQuery object has data() method, while DOM object like your xx..get(0) has no method data();
  3. So, if you want to use data() method, you must ensure the object is jQuery object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.