Code Snippet

Home » Code Snippets » JavaScript » CSS for when JavaScript is Enabled

CSS for when JavaScript is Enabled

document.documentElement.className = "js"

This adds a class to the root <html>, so you could (for example) do something like hide a <div> only when JavaScript is enabled.

.js div#id { display: none; }

Subscribe to The Thread

  1. This doesn’t add a class to the body; it adds a class to the root element (i.e. the “html” tag)…

  2. The jQuery version of this (not that you really need it, but if you’re using it anyway) is:

    $("body").addClass("js");

    I always put it right up top, with anything else that’s generic. I also usually use the class “has-js” just because a two-letter class name makes me nervous (plugins or whatnot) and it’s an eensy bit more meaningful.

    • I idea of this code is to be as fast as possible. It should be placed just below your CSS files in the head element as a plain JavaScript snippet. You’ll want to load jQuery at the bottom of your document just before the closing body tag because downloading JavaScript files blocks the rendering of the page.

      Personally I use this snippet:

      <script>(function(h){h.className = h.className.replace('no-js', 'js')})(document.documentElement)</script>

      It will replace the class of “no-js” to “js” on the HTML element while preserving all other class names that may be there.

  3. I have an additional trick for you guys; Alongside this class being Added to the body, I Remove a class that was in the body tag. So a user withOut JS will get
    <body class="xhtml">
    while a user With JS turned on will get
    <body class="js">
    ( … by removing the class ‘xhtml’ and adding ‘js’ )

    = By having a default class in the body tag it makes things easier to do “flash on load” fixes like when replacing links with Flash-content f.i., plus I find that it simplifies and prettifies the CSS a whole lot ;)

  4. I use it often to open all hidden menus, and collapse when js is enabled.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~