Using a no-js class in your WordPress theme

The no-js class can often be seen in css and html, normally placed on the html or body tag. What is it all about? It’s to be able to add specific CSS styling for those who view the site with javascript disabled. How does it work? We run a simple javascript that replaces the “no-js” class with “js”. If no javascript is enabled, no-js remains. As simple as that.

To add this to your theme, first add no-js to the html-tag of your theme’s header.php:

<html class="no-js" <?php language_attributes(); ?>>

Then, add the simple javascript to replace the no-js class with js in functions.php:

/*  Script for no-js / js class
/* ------------------------------------ */
function alx_html_js_class () {
	echo '<script>document.documentElement.className = document.documentElement.className.replace("no-js","js");</script>'. "\n";
}
add_action( 'wp_head', 'alx_html_js_class', 1 );

And there you go. You can now add .no-js .myclass { cssfix } so that your theme doesn’t break too badly if javascript is disabled.

4 Responses

  1. heide Jaimes says:

    I did not do right my kids were fighting and I did not put no-js first now i have 404 error

    • Bryan says:

      Thanks very helpful… I’ve been seeing this in themes for awhile now and haven’t been able to figure out what it was exactly for!

  2. Bryan says:

    Question actually… Do you know if any major css frameworks utilize the no-js class? Like bootstrap for instance? I’ve seen this no-js class on nearly every bootstrap wordpress theme I’ve ever looked at, but can’t find any reference to it anywhere. I’m thinking I could just remove it if I don’t personally plan on adding any no-js specific styles…. Any thoughts?

Leave a Reply to Bryan Cancel reply

Your email address will not be published. Required fields are marked *