Set background with value of data attribute

12,808

Solution 1

DEMO

$("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'));
});

http://jsfiddle.net/ZcPYv/

Share:
12,808

Related videos on Youtube

Peter Burns
Author by

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, 2022

Comments

  • Peter Burns
    Peter Burns about 2 years

    I've 16 different section-tags. Every section-tag have 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 this question CSS values using HTML5 data attribute say the answer, 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.

    Any other solutions or tips how to handle this with jQuery data()?

    • mplungjan
      mplungjan almost 11 years
      the question I really would like to ask is why not use a classname?
  • Alvaro
    Alvaro almost 11 years
    @mplungjan you can do it with both, but attr seems to be faster than data when retrieving the data.
  • andyb
    andyb almost 11 years
    +1, and I would expect just using this.style.backgroundColor = this.getAttribute('data-color'); as the function body to be even quicker.