Adding a disabled internal Style node to the HTML5 DOM: A simple guide

According to this, the style tag can be turned off using the disabled attribute. I attempted the following:

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

Both Chrome and Firefox ignore the disabled attribute and display the text in red. However, IE 11 correctly displays it in black.

Query: How can internal style nodes be added in a disabled state using JavaScript?


Background: I am dynamically loading CSS file content as a style node for processing rules with document.styleSheets.cssRules. I want to prevent the temporary loaded style from affecting the current page styles.

Although setting document.styleSheets[].disabled works, there is a delay between node insertion and being disabled.

I experimented with using

new DOMParser().parseFromString(cssFileContent, "text/html")
, which successfully loads the HTML content invisibly, but fails to initialize the document.styleSheets.

Answer №1

Instructions for incorporating internal style nodes in a disabled state using JavaScript

The HTMLStyleElement interface includes a disabled flag that can be utilized as follows:

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

If a browser does not support disabled style elements, it may not have any impact. However, this should not result in an error, as browsers without the disabled element will handle it like an "expando" property.


Context: I am dynamically loading content from a CSS file as a style node to process rules with document.styleSheets.cssRules. I aim to prevent interference with the current page styles by this temporary loaded style.

In light of the issues related to disabled style elements, you could consider using a hidden iframe instead: (live example)

<!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; }

The text appears in black, rather than red.

(Acknowledgment to mschr for providing the code to reliably add the iframe with inline HTML across different browsers.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlock the power of nested dynamic content creation with JavaScript

Every time I attempt to use getelementbyid on a dynamically loaded div, I receive null as the result. This occurs even after trying both window.onload = function () { and $(window).load(function() { index.html: <main > <div id="main-div"> ...

Voice crashes in Discord.js after the audio has been playing for a short while

Every time I try to play a song, the bot crashes and gives an "aborted" error message after about a minute. music = { "resource": createAudioResource(ytdl(parameters[0], {filter: "audioonly"}), {inputType: StreamType.Arbit ...

AngularJS directive does not trigger when switching tabs or scrolling pages

I came across a solution to display a placeholder image before the real image fully loads while browsing online here. I implemented the code provided in the accepted answer on my page, where I have two tabs using `ion-slide-box` for tab selection. Each tab ...

Filtering out strings of a certain length from an array in JavaScript

Currently working on creating a Wordle game using React. To do this, I require a list of strings. To obtain this list, I am fetching an array of strings from the following API: The challenge lies in the fact that I am interested only in words with a lengt ...

What could be the reason my dropdown menu is not appearing on hover?

Currently, I am in the process of developing a menu using angularJS and google app script within a dialog box. I have been referring to this sample code for guidance. Instead of pasting all my code here, I can summarize what I have come up with: var a ...

HTML and JavaScript: Struggling to include multiple parameters in onclick event even after escaping quotes

I am struggling to correctly append an HTML div with multiple parameters in the onclick function. Despite using escaped quotes, the rendered HTML is not displaying as intended. Here is the original HTML code: $("#city-list").append("<div class='u ...

Can you please explain the distinction between angular.equals and _.isEqual?

Do these two options offer different levels of performance? Which one excels at conducting deep comparisons? I've encountered situations where Angular's equals function fails to detect certain differences. In addition, I've observed that th ...

Should you opt for returning [something] or (nothing) in Javascript with ExpressJS?

Is there a distinct contrast between returning something and returning nothing? Let's take a look at an example: user.save(function(err){ if ( err && err.code !== 11000 ) { console.log(err); console.log(err.code); res.send(&apo ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

What is the best method for iterating through an array and generating a glossary list organized by categories?

I have an array filled with definitions. How can I use Vue.js to iterate through this array and create a glossary list organized by letters? Desired Output: A Aterm: A definition of aterm B Bterm: A definition of bterm C Cterm: A definition of cterm ...

Grabbing an AJAX Request

Currently, I am working on a Firefox extension that is designed to analyze the HTML content of web pages after they have been loaded in the browser. While I have successfully captured events like form submissions and link clicks, I am facing an issue wit ...

Leverage the power of Angular CLI within your current project

I am currently working on a project and I have decided to utilize the angular cli generator. After installing it, I created the following .angular-cli file: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": " ...

Another option could be to either find a different solution or to pause the loop until the

Is it possible to delay the execution of a "for" loop until a specific condition is met? I have a popup (Alert) that appears within the loop, prompting the user for confirmation with options to Agree or Cancel. However, the loop does not pause for the co ...

Printing content from an Angular dashboard can be achieved by following a few

Currently, I am working on developing a legal document automation program for my company. However, I have encountered an issue during the final stages of completing this web application. For the layout and setup, I am using the default angular Dashboard l ...

The React.js project I created is showcased on GitHub pages and has a sleek black design

After developing a project using React.js and deploying it on github pages, everything was functioning smoothly. However, I encountered an issue where the screen turned black after logging in and out multiple times. Are there any suggestions on how to reso ...

Implement a dropdown menu in Vue.js using data fetched from an ajax request

I am looking to utilize ajax calls in conjunction with vue.js to dynamically populate the options for a drop-down menu. Here's an example of what I currently have: <select v-model="selected"> <option v-for="option in options" v-bind:valu ...

What is the best way to denote arrays in ember-data models?

When dealing with an array in a model, is it essential to use DS.hasMany pointing to a DS.Model, even if the array elements are not actual models with IDs or endpoints? Is there a more efficient alternative? Despite using DS.hasMany with { embedded: true ...

Toggle the visibility of a div based on whether or not certain fields have been filled

Having a form with a repeater field... <table class="dokan-table"> <tfoot> <tr> <th colspan="3"> <?php $file = [ 'file' => ...

modify rectangular section in drupal rather than numerical block

Currently, I am attempting to modify blocks within my Drupal 7.x website using the Zen base theme. While I have been successful in adjusting the CSS styles of the blocks based on their numbers in the block.css file, I find this method quite confusing. Is ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...