0

As per this the style tag can be disabled with disabled attribute. I tried the below:

<head>
    <style>body { color: black; }</style>
    <style disabled>body {color: red; }</style>
</head>
<body>
    Hello World !!
</body>

Both Chrome and Firefox does not respect that disabled attribute and use the red color. IE 11 works correctly (shows black text).

Question: How to add internal style nodes in disabled state (in JS)?


Context: I am dynamically loading a css file content as a style node, to do some rule-processing with document.sytleSheets.cssRules etc. I do not want the current page styles to be affected by the presence of this temporary loaded style.

Setting document.sytleSheets[].disabled works, but there is a lag between node insertion and the disabled state.

Tried using new DOMParser().parseFromString(cssFileContent, "text/html"), which works (completely invisible) fine in loading the html content, but does not initialize the document.sytleSheets

Gopalakrishna Palem
  • 1,705
  • 1
  • 20
  • 34

1 Answers1

2

How to add internal style nodes in disabled state (in JS)?

The HTMLStyleElement interface has a disabled flag, so you'd use that:

var style = document.createElement("style");
// ...usual style stuff...
style.disabled = true;
document.querySelector("head").appendChild(style);

Of course, if a browser doesn't support disabled style elements (yet), doing that won't have any effect. It's unlikely to cause an error, though, as a browser that doesn't have the disabled element will treat it like an "expando" property anyway, so it'll be harmless.


Context: I am dynamically loading a css file content as a style node, to do some rule-processing with document.sytleSheets.cssRules etc. I do not want the current page styles to be affected by the presence of this temporary loaded style.

Since you've found issues with the level of support for disabled style elements, you might consider using a hidden iframe instead: (live copy — Stack Snippets don't allow iframes)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
<p>This text should be black.</p>
</script>
<script>
var iframe = document.createElement('iframe');
iframe.style.display = "none";
var html = "<html><head><style>body { color: red; }</style></head><body></body></html>";
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
document.body.insertAdjacentHTML(
  "beforeend",
  "First rule: " + iframe.contentDocument.styleSheets[0].cssRules[0].cssText
);
</script>
</body>
</html>

Output:

This text should be black.

First rule: body { color: red; }

...with the text in black, not red.

(Credit to mschr for the code to add the iframe with inline HTML reliably cross-browser.)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875