In the code below, I illustrated what I'm trying to achieve ... Modifying an existing CSS class by adding a new rule to it.
<head> <style> h4.icontitle {font-size: 22pt;} </style> </head> <body> <script type="text/javascript"> textpercent = 84; document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null); </script> <h4> hello </h4> </body>
This is for an element of the preliminary process of a site working on screens of different sizes. The result will be ...
h4.icontitle {font-size: 22pt; -webkit-text-size-adjust:84%;}
What will be seen when checking the DOM.
Any ideas would be most welcome. Javascript only - no jQuery here ...
solvable.
After a lot of trial and error, here is a working function that allows javascript to insert styles directly into CSS
function changeCSS(typeAndClass, newRule, newValue) { var thisCSS=document.styleSheets[0] var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules for (i=0; i<ruleSearch.length; i++) { if(ruleSearch[i].selectorText==typeAndClass) { var target=ruleSearch[i] break; } } target.style[newRule] = newValue; }
Called
changeCSS("h4.icontitle","backgroundColor", "green");
We hope others find this a useful method for using variables in their CSS in pure javascript.
source share