4

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.

1
  • 1
    Create your stylesheet inside JS file then create script tag. InnerText the stylesheet and append child to head Commented Jun 30, 2019 at 13:11

2 Answers 2

6

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 }");
Sign up to request clarification or add additional context in comments.

1 Comment

You can remove spaces inside the CSS rule: "[hidden]{display:none!important}" and around equals signs. (yeayea, I know;)
2

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>

1 Comment

Nice hacks, didn't know about them. Not sure it exactly answers the OP though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.