How to Select My CSS Module Class Using Document.Queryselector

How do I select my CSS module class using document.querySelector?

You need to select it as a class,

document.querySelector(`.${styles.scrollValue}`)

Calling styles.property returns a value such as the following,

scrollValue: '_src_styles_module__scrollValue'

So when you call document.querySelector it's looking for _src_styles_module__scrollValue which has no selector type such ., or # which makes it look for an element that would match <_src_styles_module__scrollValue> (in this case). Since there is no element with that name or the hashed name it will return null.

Working demo

How to grab a DOM element in Next.js when class name is randomized

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?

Is there a way to get all classes using document.querySelectorAll in reactjs and manipulate it?

I know of useRef() but in my case I am trying to select all buttons throughout the entire application. Not just one element in the current component.

Using .querySelector or any other selector will select only those elements that are currently rendered, actually. So if you e.g. toggle the state and component re-renders with different elements, they will not be affected with your change, which will result in partially toggled theme for different elements.

You should either set a context, wrapping whole App or set a redux variable holding info which theme is currently selected. Then, you will be able to manipulate styles using e.g. theme in styled components: https://styled-components.com/docs/advanced#theming or just toggling classNames with css modules, basing on that variable.

React CSS module not working on certain selectors

I'd say you should use className={styles[item.className] || ''}.

item.className will not refer to CSS module.

document.querySelector() is not applying style

Please see the following working snippet. Also keep in mind that AngularJS documentation discourages using controllers to manipulate the DOM.

angular.module("app", [])

.controller("demo", function($scope) {
$scope.p = document.querySelector('.bgColor');

Object.assign($scope.p.style, {
'background-color': 'red'
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<p ng-app="app" ng-controller="demo" class="bgColor">
This is dummy content
</p>


Related Topics



Leave a reply



Submit