简体   繁体   中英

Change a CSS stylesheet's selectors' properties

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.

  1. Use an external stylesheet
  2. Identify its order on the page
  3. Modify the properties of the rules

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM