7

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • Not an answer, so it goes as a comment: `attr` is for use only in `::before` and `::after` generated content: http://stackoverflow.com/a/1044862/148412 – ANeves Jul 08 '13 at 09:51
  • 1
    the question I really would like to ask is why not use a classname? – mplungjan Jul 08 '13 at 09:51
  • Because i load this sections with ajax and it's easier for me to handle it. And i think there are less lines of code when i add just 1 statement to set the background... –  Jul 08 '13 at 10:41

4 Answers4

8

DEMO

$("section").css('background', function () { //or for code's consistency, i'd use background-color instead
    return $(this).data('color')
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • 3
    Interesting approach but not that fast comparing it with an `each` loop: http://jsperf.com/each-vs-return1 – Alvaro Jul 08 '13 at 09:59
  • @Steve That's correct, i appreciate this kind of comment :) Even in your case, you should use object data not attribute. – A. Wolff Jul 08 '13 at 10:07
  • Thank you both for your answer / comment. Combined, the best solution! `+1` to both of you :P –  Jul 08 '13 at 10:45
3

Try this code,

$("section").each(function(){
    $(this).css('background',$(this).data('color'));
});

http://jsfiddle.net/ZcPYv/

Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
3

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/

Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • @mplungjan you can do it with both, but `attr` seems to be faster than `data` when retrieving the data. – Alvaro Jul 08 '13 at 10:08
  • 1
    `+1`, and I would expect just using `this.style.backgroundColor = this.getAttribute('data-color');` as the function body to be even quicker. – andyb Jul 08 '13 at 10:24
0

Try this out:- http://jsfiddle.net/adiioo7/JgfkY/

JS:-

jQuery(function($){
    $("#section").css("background-color",$("#section").attr("data-color"));
});

HTML:-

<section id="section" data-color="#A3D1B5">Section with custom color</section>
Aditya Singh
  • 9,512
  • 5
  • 32
  • 55