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?
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.