'Javascript Selector' for CSS

Sometimes you want to selectively display certain elements on a webpage depending on whether or not the user has Javascript enabled. Here’s a neat trick to do so!

  1. Add the no-js class to the html element:

    <html class="no-js">
      ...
    </html>
  2. Load the following Javascript code:

    document.documentElement.classList.remove("no-js");
    document.documentElement.classList.remove("js");
  3. Include the following CSS:

    :root.no-js .when-js {
       display: none !important;
    }
    
    :root.js .when-no-js {
      display: none !important;
    }

Now you can add the when-js/when-no-js class to elements to only show it when Javascript is enabled/disabled!