Reputation:
I have 16 different section
-tags. Every section
-tag has a data-
attribute to set a specific background-color for each section
:
<section data-color="#A3D1B5">
Now I want to set this color as the background.
What I've already tried:
In CSS values using HTML5 data attribute, the answer says it should be possible to set the color like background: attr(data-color);
, but this won't work for me.
I took a look at jQuery data()
but I don't know how to set the background for all of the section
-tags.
Are there any other solutions to handle this with jQuery's .data()
?
Upvotes: 7
Views: 14644
Reputation: 74420
$("section").css('background', function () { //or for code's consistency, i'd use background-color instead
return $(this).data('color')
});
Upvotes: 8
Reputation: 9612
JS:-
jQuery(function($){
$("#section").css("background-color",$("#section").attr("data-color"));
});
HTML:-
<section id="section" data-color="#A3D1B5">Section with custom color</section>
Upvotes: 0
Reputation: 41595
You have to get the data-color
attribute and assign it to the background
in the css:
$('section').each(function(){
$(this).css('background', $(this).attr('data-color'));
});
Living example: http://jsfiddle.net/Pk5dK/
Upvotes: 3
Reputation: 24302
Try this code,
$("section").each(function(){
$(this).css('background',$(this).data('color'));
});
Upvotes: 3