'How to grab a DOM element in Next.js when class name is randomized [duplicate]
I'm building a Next.js app (v 12.1.0) and in my Nav component, I'm trying to grab a DOM element with
const nav = document.querySelector('.nav');
This returns an error
TypeError: Cannot read properties of null (reading 'classList')
because this element gets rendered as
<div class="Nav_nav___cOea"></div>
instead of the .nav class that I use in my CSS.
I'm using css modules and sass, so my CSS is in Nav.module.sass (which loads just fine), however, as you see above, it gets rendered with a different class name. How do I grab the rendered element? Or how do I stop next.js from randomizing class names?
Solution 1:[1]
The solution is to refer to the class in the querySelector like so:
const nav = document.querySelector(`.${styles.nav}`);
This assumes that styles were imported like so:
import styles from '../styles/Nav.module.sass';
This is based on the accepted response to this question: How do I select my CSS module class using document.querySelector?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | night_train |
