Dynamically change a class background

Asked

Viewed 1,390 times

3

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

I have a class in my CSS as follows:

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

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

  • Explain better what you are trying to do, because it is not clear.

  • I have a site where the content creation is dynamic and the user can choose the color to be used in components, but, I need him to see the update in real time, then, I need the class to be changed with the necessary value and the added elements also gain that change

  • Caio, I edited my answer, see if this solution serves.

  • 1

    not from @Paulomaciel but Sergio’s is exactly what I needed :D

  • I removed the solution that I had put in since it is not changing the future elements, but added a complement to Sergio’s reply.

2 answers

4


If you have the CSS inside the HTML you can do so:

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

Example

The selector $('style') go find the <style> and change its content. Note that this method can be "brute force", so I suggest having only the minimum required in HTML

  • 1

    That solved my problem, thanks :D

3

Just complementing Sergio’s response if you don’t use the tag style in your HTML, you can do 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 CSS separate initial from your HTML.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.