Change background of a class dynamically

3

I have a site where content creation is dynamic and the user can choose the color to be used in components, but I need it to see the update in real time, so I need the class to be changed with the required value and that the added elements also win this change.

I have a class in my CSS as follows:

<style type="text/css">
    .color
    {
        background: red;
    }
</style>

How do I change the background of this class dynamically so that all elements receive the new value of background and the next elements to be created already come with this element?

    
asked by anonymous 08.05.2014 / 00:01

2 answers

4

If you have CSS inside HTML you can do so:

var style = $('style').text();
var newStyle = '.color {color: red; }';
$('style').text(newStyle);

Example

The $('style') selector will search for <style> and change its contents. Note that this method can be "brute force", so I suggest you have only the minimum required in HTML

    
08.05.2014 / 00:13
3

Just complementing Sergio's response, if you do not use the style tag in your HTML, you can do it as follows:

if($('style').length){
    var style = $('style').text();
    var newStyle = '.color {color: red; }';
    $('style').text(newStyle);
}else{
    $( "<style>.color {background-color : red}</style>" ).appendTo( "head" )
}

So you can put your initial%% of your initial% of your HTML.

    
08.05.2014 / 00:44