Use Different CSS When Javascript Is Enabled

Here is a snippet that allows you to have different CSS for when Javascript is turned on or off. You may need different CSS so you can deal with visitors who have Javascript turned off, you may want to display things differently.

To change how you display different CSS for when Javascript is on you can add a CSS class to the html tag so you can filter the CSS down to the child tags.


Here is a raw Javascript way to add a CSS class if Javascript is turned on.

document.documentElement.className = "js";

This will change the HTML tag to

<html class="js">


If you use jQuery then you can just use the following which will do the same thing.


Change The CSS

Now you have a CSS class on the HTML tag you can change the child elements.

.slides { display:block; }
.js .slides { display:none; }

This will change the slides element to hidden if Javascript is turned on which means you can add the functionality of the slideshow with the Javascript.

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial