Myforwik
Myforwik

Reputation: 3588

How to dynamically change the value of a CSS property inside a stylesheet?

If I have css:

.myclass
{
background: #FF00FF;
}

And html:

<div class="myclass">etc.</div>
<div class="myotherclass">etc.</div>
<div class="myclass">etc.</div>

How can I change the background variable of myclass to another color, so that all div's of that class get their background changed?

no jquery please, thanks

Upvotes: 3

Views: 4883

Answers (2)

user8373067
user8373067

Reputation:

Hope I am close to what you are expecting when I say You may please try something like this:-

$(document).ready(function(){
    $("button").click(function(){
        $("div").toggleClass("myclass");
    });
});
.myclass
    {
       background: #FF00FF;
    }
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>
<body>

<button>Set the color property of all p elements</button>

<div class="myclass">etc.</div>
<div class="myotherclass">etc.</div>
<div class="myclass">etc.</div>



</body>
</html>

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185923

Here you go:

[].every.call( document.styleSheets, function ( sheet ) {
    return [].every.call( sheet.cssRules, function ( rule ) {
        if ( rule.selectorText === '.myclass' ) {
            rule.style.backgroundColor = 'green';
            return false;
        }
        return true;
    });
});

Live demo: http://jsfiddle.net/gHXbq/

ES5-shim for IE8

Upvotes: 5

Related Questions