Reputation: 1346
Here's how we traditionally change the style of a recurring element.
Applying the style to each element
function changeStyle(selector, prop, val) {
var elems = document.querySelectorAll(selector);
Array.prototype.forEach.call( elems, function(ele) {
ele.style[prop] = val;
});
}
changeStyle('.myData', 'color', 'red');
Using classes to supersede the existing style
function addClass(selector, newClass) {
var elems = document.querySelectorAll(selector);
for (let i=0; i<elems.length; i++) {
elems[i].classList.add(newClass);
};
}
addClass('.myData', 'redText');
Instead, I want to change the actual stylesheet's selectors' properties (such as directly modifying a class). I don't want to loop through the elements that match my selector and apply the CSS directly nor add a modifier class to the elements.
Upvotes: 9
Views: 10393
Reputation: 1346
Here's how to do that:
// ssMain is the stylesheet's index based on load order. See document.styleSheets. E.g. 0=reset.css, 1=main.css.
var ssMain = 1;
var cssRules = (document.all) ? 'rules': 'cssRules';
function changeCSSStyle(selector, cssProp, cssVal) {
for (i=0, len=document.styleSheets[ssMain][cssRules].length; i<len; i++) {
if (document.styleSheets[ssMain][cssRules][i].selectorText === selector) {
document.styleSheets[ssMain][cssRules][i].style[cssProp] = cssVal;
return;
}
}
}
Make sure that the rule that you want to modify already exist in the CSS file and are in the correct cascading order, even if they're empty. Otherwise, if a selector doesn't have a rule, you would have to use document.styleSheets[index].insertRule()
for which you would have to specify where in the list of rules should the rule be inserted.
changeCSSStyle('.warning', 'color', 'red');
changeCSSStyle('td.special', 'fontSize', '14px');
Upvotes: 12