Reputation: 8705
Say I have this little snippet:
<p data-color="red">Hello world</p>
An I want to set its color to its own data-attribute, like this:
$('p').css({
color: $(this).data('color')
});
For some reason, that doesn't work. Anyone know what I'm doing wrong?
Upvotes: 1
Views: 842
Reputation: 5286
You could store the whole data in an object before setting the css properties to avoid a loop. Something like :
var $p = $('p'),
data = $p.data();
$p.css({
color: data.color,
fontSize: data.fontSize
});
Upvotes: 2
Reputation: 2881
$('p').css('color', function() {
return $(this).data('color');
});
Upvotes: 3
Reputation: 190925
this
refers to something else, not to the p
. Try putting it in a function.
$('p').css('color', function() { return $(this).data('color'); });
Upvotes: 3