javascriptcssmobile-chrome

Modifying of css by document.styleSheets


I try to modify CSS by changing:

document.styleSheets[0].cssRules[0].style.fontSize = '1rem';

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.


Solution

  • Modifying styleSheets directly can be tricky.

    I prefer to append a new style element to the document and place the modified CSS in there. Since it is the last style element in the document, it will override any earlier CSS rule that has a matching selector.

    For example, this will set the font size of the body to 1rem:

    let style = document.createElement('style');
    style.innerHTML = 'body { font-size: 1rem; }';
    document.head.appendChild(style);