Fastest method for inserting CSS rules using pure JavaScript

I've been developing a library with a strict size limit of 1KB, and I'm almost hitting that threshold. My challenge now is to implement a CSS rule for controlling the show/hide behavior.

[hidden]{ display:none !important }

The HTML page does not contain any style tags, so this single rule is all I need. However, I can only add it using pure JavaScript. I prefer not to change an element's style directly with el.style.display = 'none', but instead want to manipulate it through an attribute.

Has anyone discovered a more efficient approach than creating a style element, setting its innerHTML, and appending it to the head element? I'd love to hear a clever solution that minimizes character usage.

Answer №1

This is the shortest code I managed to write, feel free to make it even shorter.

const addCustomCSS = styleString => document.head.appendChild(document.createElement("style")).innerHTML = styleString;

// Example of usage:
addCustomCSS("[hidden]{ display:none !important }");

Answer №2

To conceal an element using an attribute, you can simply apply the hidden attribute.

For instance:

<div hidden class="container"></div>

If you prefer not to use el.style.display = 'none', another approach is to utilize cssText to input your entire style in a single string.

For example:

document.querySelector('.container').style.cssText = 'width: 100vw; height: 100vh; background: rebeccapurple;';
<div class="container"></div>

Alternatively, you could consider utilizing the method CSSStyleSheet.insertRule().

The CSSStyleSheet.insertRule() method adds a new CSS rule to the current stylesheet, with some limitations.

For example:

const css = window.document.styleSheets[0];
css.insertRule(`
  .container {
    width: 100vw;
    height: 100vh;
    background: rebeccapurple;
  }
`, css.cssRules.length);
<div class="container"></div>

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

Python Webscraping using Selenium

I'm experiencing difficulties webscraping the list of DAOs from masari.io due to some errors that I encountered: DeprecationWarning: executable_path has been deprecated, please pass in a Service object driver = webdriver.Chrome(options=options, exec ...

Scrollable Bootstrap navigation bar

I'm attempting to modify the Bootstrap navbar's behavior so that it utilizes a horizontal scroll instead of collapsing. While this works on mobile devices, I want it to function the same way on all devices using SASS: .navbar-nav { li { di ...

I'm experiencing difficulty in loading a static HTML page from the app file when using Node.js

I'm currently working on setting up a system where an HTML page is loaded upon request to the app. Although I've managed to get the HTML to load successfully using res.end('') within the server definition, I find this method to be messy ...

I am facing an issue where the URL generated in the Controller in Laravel is not functioning properly when

After escaping the single quote, I included a URL link inside the Controller and passed it through json_encode. However, when I clicked on the URL link, it did not work and showed this: https://i.sstatic.net/3GIq1.png The URL appeared like this: http: ...

Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...

Having trouble loading a model with GLTFLoader in Vue2

I am utilizing GLTFLoader to import a model into my Vue2 application. My implementation follows the standard Three.js template. I directly copied the GLTFLoader code from the Three.js documentation. Despite creating a simple example, I am facing difficulti ...

Troubleshooting the issue of array filtering not functioning properly in Async.js

When attempting to utilize async's filter method, I am not receiving the expected result. Could someone point me in the right direction? async.filter([1, 3, 5], function (item, done) { done(item > 1); }, function (results) { con ...

How can I display the value of a variable within an Angular 4 component directly from the console?

In my Angular 4 component, I store a simple key in a variable. However, I am aware that when the app is closed, all values within the variable are erased. Here is an example of this: export class LoginComponent implements OnInit { data : any; const ...

Retrieving multiple checkbox values from the front end using AJAX and passing them to

I have some code for ajax that is causing me issues. Here it is: var userCheckbox = $("input[name=chk]:checked").val(); This is the checkbox section in my html: <input id="checkbx" type="checkbox" name="chk" value="apple"/>apple</td> <inp ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

Positioning the jQuery mobile navBar to be fixed on iOS 4 devices

Currently working on a mobile app with jquery using iOS4 and iOS5 compatibility as the final hurdle. While fixing the navigation bar is simple on iOS5 with position:fixed, it's not as straightforward on iOS4! I've experimented with various soluti ...

Performing subtraction on two time values with AM/PM formatting using JavaScript

I'm currently using a date.js plugin to convert my times into date objects and then trying to subtract them. However, the result is not showing as valid. The time format I am working with is 11:00 pm. Here is the code snippet: var tim_i = $('#in ...

Using a background image in a PyQt4 QLabel

After making modifications to a simple countdown timer found here, I am now trying to add a background image behind the countdown timer. Does anyone have suggestions on how to accomplish this? #!/usr/bin/python import sys from PyQt4.QtCore import Qt, ...

Align the "link text" vertically in the middle of the list item and resize the text to fit the list container proportionally

Hey there, I hope the title of my page makes sense! I created a full-page navigation menu wrapped in a list as it should be... I think. Now, I have a few queries: 1. How can I vertically center the links within the list items? 2. Is it possible to mak ...

Executing the serverless invoke local command produces no output

Attempting to locally run a node lambda for debugging purposes. Utilizing Serverless and the provided launch configuration in vsCode. { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launc ...

What could be the reason behind encountering a "Cannot return null for non-nullable field" error while attempting a mutation?

Exploring (Apollo) GraphQL on the server side has presented me with a puzzling issue. I have been attempting to register a user, but I keep encountering the error documented in the linked image below. What could be causing this problem? Let's disregar ...

The error undefinedspan is being thrown when using document.getElementById.value in conjunction with a span tag

While using document.getElementById.value on an input tag, I'm getting the correct value. <td ><input id="testing" data-bind="value: SPL_ApprovalDetailsObj.TgtSales "> </span></td> However, when I try the same with a span tag ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

Avoid sending a set of radio buttons within a form

In the form I'm working on, there are some check boxes and a radio group. I recently removed the 'name' attribute from the check boxes to avoid them being submitted. However, I realized that radio buttons require a name attribute for identif ...

Custom sorting in JavaScript

I have a specialized sorting method that is defined as follows sortArrayBy: function(a, b, sortKey) { if (a[sortKey] < b[sortKey]) return -1; if (a[sortKey] > b[sortKey]) return 1; return 0; }, I am looking to enhance it ...