Nyxynyx
Nyxynyx

Reputation: 63727

Getting data- attributes using jQuery

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

Answers (6)

Steven
Steven

Reputation: 25

  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.

Upvotes: 0

PhearOfRayne
PhearOfRayne

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

Patrick Gunderson
Patrick Gunderson

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

kjana83
kjana83

Reputation: 398

use .attr() function. Like

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

Upvotes: 0

xdazz
xdazz

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

Sridhar Narasimhan
Sridhar Narasimhan

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

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

Upvotes: 0

Related Questions