I have the following situation:
.my-nice-class {
max-width: 90%;
max-height: 90%;
}
This code lies in the first <style>...</style>
in the html page.
I would like to override this global css, by setting for instance new properties values like in the example below:
.my-nice-class {
max-width: 40%;
max-height: 40%;
}
How can I accomplish this with pure Javascript?
Thank you all,
Nano
Modify the css as you want by modifying this object
document.getElementsByTagName("style")[0].innerHTML
OR
Modify style attribute of relevant DOM objects
document.getElementsByClassName("my-nice-class").style[0] = "max-width: 40%;max-height: 40%;"
NOTE: You have to use a for loop instead of style[0]
if you have multiple objects.
For a scalable solution to this problem you could also consider to go for a BEM implementation where you will add and remove modification classes.
//HTML
<div class='my-nice-class my-nice-class--dimensions_A'></div>
Then the css:
CSS:
.my-nice-class--dimensions_A {
max-width: 90%;
max-height: 90%;
}
.my-nice-class--dimensions_B {
max-width: 40%;
max-height: 40%;
}
Then the javascript can add and remove this classes
//Javascript
var htmlEl = document.getElementsByClassName('my-nice-class')[0]; // in case you need the first element from the elements array
htmlEl.classList.add("my-nice-class--dimensions_B");
htmlEl.classList.remove("my-nice-class--dimensions_A"); // cleaner but optional, since cascading character of css will render --B first anyway at this point
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With