Search code examples
htmljquerycsscustom-data-attribute

Set background color based on the value of a data attribute


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()?


Solution

  • DEMO

    $("section").css('background', function () { //or for code's consistency, i'd use background-color instead
        return $(this).data('color')
    });