'How to apply CSS to newly loaded Document
I would like to load a document using fetch() and then apply CSS styles to it.
However, it doesn't seem like I can inspect the styles unless I append the document to the main one, as seen here:
const doc = fetch(); // get some document
doc.documentElement.computedStyleMap() // returns an empty map
document.appendChild(doc.documentElement) // attach it to the main document object
doc.documentElement.computedStyleMap() // now populated
Is there any way I can call some method to get the CSS cascade to happen, populating the computedStyleMap without attaching it as done in step 3?
Solution 1:[1]
I would like to load a document using fetch() and then apply CSS styles to it.
I've tested this locally and it seems computedStyleMap only works for documents / elements that are actually attached in the DOM.
An alternative is using the styleSheets API.
var styleSheet = document.styleSheets[0];
styleSheet.insertRule('.myclass{ color: 'red'; }', styleSheet.cssRules.length);
Keep in mind that if you load a stylesheet from another domain, like a CDN, you may need to select a different index of the .styleSheets to use one on your domain. Otherwise you may encounter security errors.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Olaf |
