How do I add the class name "foo" to the root <html>
element without using jQuery (or a similar library)?
Asked
Active
Viewed 5.2k times
44

j08691
- 204,283
- 31
- 260
- 272

user940633
- 479
- 1
- 4
- 3
-
6So many duplicates... – Zirak Sep 12 '11 at 13:27
-
@CoryMawhorter [Manipulating classes](http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript/196038#196038), [grabbing the html element](http://stackoverflow.com/questions/9362907/how-can-i-reference-the-html-elements-corresponding-dom-object/9362944#9362944) – Zirak May 22 '13 at 00:37
3 Answers
64
You can use the classList to access an element's list of classes.
document.documentElement.classList.add('my-awesome-class');
document.documentElement.classList.remove('my-awesome-class');
document.documentElement.classList.contains('my-awesome-class');

Oliver
- 4,471
- 2
- 21
- 18
-
2Use with caution, classList partially supports explorer browsers: http://caniuse.com/#search=classList – Elad Levy Apr 11 '16 at 07:25
61
Just get the element and append to the list of classes.
document.documentElement.className += " foo";

Quentin
- 914,110
- 126
- 1,211
- 1,335
-
4Thank you! It's crazy how you can do so much stuff with jQuery without knowing anything about basic JavaScript… Sorry if this had been asked a million times before, I only managed to find jQuery-based solutions. – user940633 Sep 12 '11 at 13:42
-
When I use the `-=` operator in the same way to remove a class, I get a `NaN` in the class name, instead of nothing (JS auto-converts to numbers when using `+` and `-` operators?). Of course, if you have just one class, you can simply do `= "";` to remove it, but [the answer by Olivér Kovács](https://stackoverflow.com/a/22224493/1765386) is the best in my case. – Anderson Feb 19 '16 at 12:53
-
1@Anderson In JS when you use `+=` it concatenates the two strings `document.documentElement.className` and `" foo"` but there is no `-` operator for strings in JavaScript. As a result, the interpreter implicitly converts the strings `document.documentElement.className` and `" foo"` to numbers which results in `NaN`s. The result of `NaN - NaN` is `NaN`. You can see the same result by doing: `"hello" - "foo"` in a Chrome console. – Jeremy Wiebe Jul 29 '16 at 17:22
-
1a simple change to ensure it's always cleanly added to is to use " foo " with spaces before AND after, so if others end up doing it in a bad way, your class is still good. – Brad Parks Jan 20 '17 at 14:16
5
AddClass(document.documentElement, 'my-awesome-class', true); //add
AddClass(document.documentElement, 'my-awesome-class', false); //remove
function AddClass(o,c,bAdd){
var list = o.className.split(" ");
if (list.indexOf(c)!==-1){
if (!bAdd) delete list[list.indexOf(c)];
}else{
if (bAdd) list[list.length] = c;
}
o.className = list.join(" ");
}

Igor Krupitsky
- 787
- 6
- 9