chickens
chickens

Reputation: 22304

Shortest way to add CSS rules with vanilla JS

I'm working on a library that I'm trying to keep it below 1KB. Which I'm already very close to my limits. I need to add a css rule to control show hide behaviour.

[hidden]{ display:none !important }

HTML page does not have any style tags. This will be only rule I need. I can only add it with pure JS. I do not want to change the style of an element with el.style.display = 'none'. I want to do it with an attribute.

So how can I add this, I found solutions that create a style element and set it's innerHTML and append it to head element. I'm hoping I can get an answer / a hack to maybe do it with less characters.

Upvotes: 3

Views: 3045

Answers (2)

chickens
chickens

Reputation: 22304

This is the shortest I got, please make it shorter if you can.

const addCSS = s => document.head.appendChild(document.createElement("style")).innerHTML = s;

// Usage:
addCSS("[hidden]{ display:none !important }");

Upvotes: 5

Reza Saadati
Reza Saadati

Reputation: 5421

If you want to hide an element with an attribute, simply use the attribute hidden.

Example:

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

If you do not want to use el.style.display = 'none', you could also use cssText to use your whole style in only 1 string.

Example:

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

Another option would be using the method CSSStyleSheet.insertRule().

The CSSStyleSheet.insertRule() method inserts a new CSS rule into the current style sheet, with some restrictions.

Example:

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

Upvotes: 1

Related Questions