Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to <html> with Javascript?

How do you add a class to the <html> root element using Javascript?

like image 917
Brandon Lebedev Avatar asked Dec 20 '12 21:12

Brandon Lebedev


People also ask

Can you add a class to HTML?

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

Can you add a class in JavaScript?

JavaScript provides 2 different ways by which you can add classes to HTML elements: Using element. classList. add() Method.


2 Answers

Like this:

var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)  root.setAttribute( 'class', 'myCssClass' ); 

Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)

root.className += ' myCssClass'; 

Or, depending on the required browser support, you can use the classList.add() method:

root.classList.add('myCssClass'); 

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist

UPDATE:

A more elegant solution for referencing the HTML element might be this:

var root = document.documentElement; root.className += ' myCssClass'; // ... or: //  root.classList.add('myCssClass'); // 
like image 149
Kevin Boucher Avatar answered Oct 09 '22 00:10

Kevin Boucher


This should also work:

document.documentElement.className = 'myClass'; 

Compatibility.

Edit:

IE 10 reckons it's readonly; yet:

It worked!?

Opera works:

Works

I can also confirm it works in:

  • Chrome 26
  • Firefox 19.02
  • Safari 5.1.7
like image 31
c24w Avatar answered Oct 08 '22 23:10

c24w