Reputation: 1514
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.
Upvotes: 1
Views: 4013
Reputation: 895
put title instead of data-title.
$(function(){
$('#titledata').text($('.backgroundImages:first-child').data('title'));
});
Running example is here
http://jsfiddle.net/rajeshmepco/ud6Ww/1/
Upvotes: 1
Reputation: 123739
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
Upvotes: 3
Reputation: 27382
Replace
.data("data-title");
with
.data("title");
OR
.attr("data-title");
Upvotes: 2