1

i am trying to grab the data attribute of an element but somehow it says undefined. here is my html code

 <div id="imageContainer">
    <img data-fullimageid="1" data-title="Cool Stuff" class="backgroundImages" src="images/galvanize/1.jpg" />
    <img data-fullimageid="2" data-title="Awesome" class="backgroundImages" src="images/galvanize/1336/dj.jpg" />
    <img data-fullimageid="3" data-title="Elite" class="backgroundImages" src="images/galvanize/3.jpg" />
</div>

And using Jquery to alert it

    var firstImageTite = $('.backgroundImages:first-child').data("data-title");
alert(firstImageTite);

it says Undefined. Please tell me where i am wrong, thanks.

3 Answers 3

3

Just do

$('.backgroundImages:first-child').data("title");

instead of

$('.backgroundImages:first-child').data("data-title");

jquery .data caches the value of the data-* into the key with the name that appears after data-. So while using setter and getter of jquery data api, you just need to mention the attribute name (without prefix).

Also do note that any changes you make using .data does not change the actual attribute value, so once modified with .data api retrieve it with .data api as well

Sign up to request clarification or add additional context in comments.

Comments

2

Replace

.data("data-title");

with

.data("title");

OR

.attr("data-title");

Comments

1

put title instead of data-title.

$(function(){
$('#titledata').text($('.backgroundImages:first-child').data('title'));
});

Running example is here

http://jsfiddle.net/rajeshmepco/ud6Ww/1/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.