Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a class to the <html> element without jQuery?

How do I add the class name "foo" to the root <html> element without using jQuery (or a similar library)?

like image 227
user940633 Avatar asked Sep 12 '11 13:09

user940633


People also ask

Can I add a class to the HTML element?

HTML. Using . add() method: This method is used to add a class name to the selected element.

How do I add a class to an element in CSS?

If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size.

Can we use JavaScript without jQuery?

Don't get me wrong - jQuery is still a wonderful library and most often than not you will be better off using it. However, for smaller things like simple pages with limited JS interactions, browser extensions and mobile sites, you can use vanilla JS.


2 Answers

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'); 
like image 67
Oliver Avatar answered Sep 21 '22 20:09

Oliver


Just get the element and append to the list of classes.

document.documentElement.className += " foo"; 
like image 28
Quentin Avatar answered Sep 23 '22 20:09

Quentin