Set background with value of data attribute
Solution 1
$("section").css('background', function () { //or for code's consistency, i'd use background-color instead
return $(this).data('color')
});
Solution 2
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/
Solution 3
Try this code,
$("section").each(function(){
$(this).css('background',$(this).data('color'));
});
Related videos on Youtube
Peter Burns
Stack Overflow Valued Associate #00001 Wondering how our software development process works? Take a look! Find me on twitter, or read my blog. Don't say I didn't warn you because I totally did. However, I no longer work at Stack Exchange, Inc. I'll miss you all. Well, some of you, anyway. :)
Updated on June 17, 2022Comments
-
Peter Burns about 2 years
I've 16 different
section
-tags. Everysection
-tag have adata-
attribute to set a specific background-color for eachsection
:<section data-color="#A3D1B5">
Now I want to set this color as the background.
What i've already tried
In this question CSS values using HTML5 data attribute say the answer, it should be possible to set the color likebackground: 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 thesection
-tags.Any other solutions or tips how to handle this with
jQuery data()
?-
mplungjan almost 11 yearsthe question I really would like to ask is why not use a classname?
-
-
Alvaro almost 11 years@mplungjan you can do it with both, but
attr
seems to be faster thandata
when retrieving the data. -
andyb almost 11 years
+1
, and I would expect just usingthis.style.backgroundColor = this.getAttribute('data-color');
as the function body to be even quicker.