Kriem
Kriem

Reputation: 8705

How to set the css properties with its own data-attributes?

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

Answers (3)

Leo
Leo

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
});​

http://jsfiddle.net/aYpXZ/

Upvotes: 2

The System Restart
The System Restart

Reputation: 2881

​$('p').css('color', function() {
    return $(this).data('color');
});​​

DEMO

Upvotes: 3

Daniel A. White
Daniel A. White

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

Related Questions