Skip to content

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.

Answer

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 }");