Isaiah M Fisher
Isaiah M Fisher

Reputation: 151

VueJS add/remove class to <html> tag

I am working on creating themes in VueJS right now. I have a themes.less file that executes a function upon change of <html> tag class. I want to be able to programmatically swap the theme based on selected option in a dropdown. When the dropdown is set to 'Dark' I want the .dark class added to my <html> tag. So far, I have not found a way to manipulate the root <html> tag from VueJS. Is it possible to add and remove classes from this tag without adding JQuery to the project?

Upvotes: 0

Views: 1440

Answers (1)

Pascal
Pascal

Reputation: 354

Is it possible to add and remove classes from this tag without adding JQuery to the project?

You can use pure JavaScript.

document.documentElement.classList.add("MyClass");
document.documentElement.classList.remove("MyClass");

or

document.querySelector('html').classList.add("MyClass");
document.querySelector('html').classList.remove("MyClass");

If you want to use the body instead of html tag:

document.body.classList.add("MyClass");
document.body.classList.remove("MyClass");

or

document.querySelector('body').classList.add("MyClass");
document.querySelector('body').classList.remove("MyClass");

The only reason this is acceptable in VueJS, is because the HTML and BODY tag are outside of the template of VueJS thus wouldn't conflict with the framework.

Upvotes: 2

Related Questions