Skip to content
Advertisement

Error when trying to target and add classes to html, body, and __nuxt elements in Vue/Nuxt

I’m getting the error “cannot read property ‘classList’ of null” when trying to add/remove classes using document.getElementsByTagName('html').classList, and also for any other high-level elements in the skies above Component Land, such as body or __nuxt.

Running in mounted() lifecycle with nextTick function.

Also tried checking process.client, but no luck either.

Any ideas?

Thanks : )

Advertisement

Answer

From my comment above, you probably intended to use:

document.getElementsByTagName("html")[0]
document.getElementsByTagName("body")[0]

Just so you are aware, there are stored properties that reference the common HTML tags so you don’t need to do any lookups:

document.documentElement  // <html>
document.body             // <body>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement