Change background of a class dynamically

Posted on

Question :

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?

    

Answer :

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

    

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.

    

Leave a Reply

Your email address will not be published. Required fields are marked *