Majonsi Majonsi - 1 year ago 36
Javascript Question

Change CSS properties of an element not in the DOM

I'm trying to add a css property to an element with the following command:


is calculated when the page is loaded.

The problem is that the
class is not present in the DOM when the page is loaded, pinned class is add to an element after the user had scroll. So, the command doesn't work.

How can I set the
css property when the page is loaded but not present in the DOM?

Answer Source

You can dynamically add CSS rules via JavaScript:

document.styleSheets[0].insertRule('.pinned { left: ' + colPositionLeft + 'px; }', 0);

adds the the rule as the first rule. To add it as the last rule you can use

var styleSheet = document.styleSheets[0];
styleSheet.insertRule('.pinned { left: ' + colPositionLeft + 'px; }', styleSheet.cssRules.length);

Both examples add the rule to the first style sheet (included file or <style> tag in the document) which should usually be sufficient. You can of course use other elements in document.styleSheets to add it to another.

Note that if you try to do this with a cross-origin style sheet it will throw a SecurityError in at least some browsers.