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.
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.
4 Answers
Reset to default 9replace
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.
The accepted answer is indeed correct, but this way will replace all classes of the <html>
, not only .no-js
.
This little script will do the same thing, but will instead search only for the no-js
class and rewrite it.
document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js ';
Took script from here, very simple! http://snipplr.com/view/63895/remove-nojs-class-from-html-tag-add-js-class/
You forgot to assign the html.className
to the new value:
var html = document.getElementsByTagName("html")[0];
if(html.className == "no-js") {
html.className = html.className.replace("no-js", "js"); // user has JS enabled
}
With a little regex
(function(html) {
html.className = html.className.replace(/\bno-js\b/, 'js')
})(document.documentElement);
<!DOCTYPE html>
<html class="no-js">
<head>
</body>
</html>
html.className = html.className.replace("no-js", "js");
– JJJ Commented Feb 16, 2013 at 17:14