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.
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.
Share Improve this question asked Jun 30, 2019 at 12:31 chickenschickens 22.4k7 gold badges61 silver badges57 bronze badges 1-
Create your stylesheet inside JS file then create
script
tag. InnerText the stylesheet and append child tohead
– Sergey Commented Jun 30, 2019 at 13:11
2 Answers
Reset to default 5This 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 }");
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>