Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override global css with pure javascript

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

like image 591
Nano Avatar asked Feb 10 '17 09:02

Nano


2 Answers

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.

like image 177
TRiNE Avatar answered Sep 30 '22 06:09

TRiNE


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
like image 44
melvinv Avatar answered Sep 30 '22 05:09

melvinv