javascriptvue.jsnuxt.jsgetelementsbytagname

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 : )


Solution

  • 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>