Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Replacing "no-js" class with "js" class not working?

I placed a class in my <html> element called "no-js". This indicates that the user isn't using javascript, (whether it be disabled or blocked). And then, in a script file I created, I want to revoke "no-js" and inject "js" so that I can determine if the user is using javascript or not via classes. I tried using the replace() method by querying the html tag, but it isn't working. Here's what I have:

var html = document.getElementsByTagName("html")[0];
if(html.className == "no-js") {
    html.className.replace("no-js", "js"); // user has JS enabled
} 

There are no errors in Google Chrome or Firefox's bug console, but neither is it changing no-js to js. I would use the <noscript> tag but I like to keep the markup side of it clean.

like image 675
Jace Cotton Avatar asked Feb 16 '13 17:02

Jace Cotton


1 Answers

replace returns the new string, it doesn't modify the original.

Try html.className = 'js', since you've already established that it's the only class name with your if statement.

EDIT: Also, the <html> tag is already available as document.documentElement.

document.documentElement.className = 'js';

That's all you need, really. No if statement, no variable, nothing.

like image 177
Niet the Dark Absol Avatar answered Nov 11 '22 04:11

Niet the Dark Absol