7

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

Community
  • 1
  • 1
  • 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
  • 73,242
  • 9
  • 90
  • 149
  • 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
  • 22,932
  • 5
  • 63
  • 83
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
  • 39,293
  • 27
  • 153
  • 316
  • @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,431
  • 5
  • 31
  • 54