There are various different ways to dynamically change the appearance of HTML elements. The easiest way to do this is to use getElementById() method on the native document interface. The argument to this method should be the ID of the element you want to select.
Once you have selected the element, then set the class property to a className value you want to set.
Using CSS only
Sometimes you want to specify the component’s style when it is focused, or when a mouse hovers over it. In this case, you can use the :hover selector in addition to normal selectors. It can be paired with element selectors, class selectors, as well as id selector.
You can also use CSS to specify styles for certain resolutions of the screen. These are called media queries. You can specify CSS styles for mobile screens, tablets, smaller laptop screens, and large monitors. This is a great feature, because it allows you to build responsive web pages. Back in the old days, the layout of HTML page was the same for all screen sizes. Screen sizes are much more diverse today.
Perhaps the easiest way to dynamically change HTML element’s appearance is to use a front-end framework. React, Vue and Angular are three most popular options. I have the most experience with React, so that’s the one I will discuss.
State is essential for making all of this work. ‘Changeable’ data like user inputs is stored in the state. We conditionally set className and inline styles depending on values in the state. Whenever these values change, React automatically rerenders the entire component tree. So if a user checks ‘dark mode’, that will trigger the change in the state, which will rerender the entire component tree. Once it is rendered, React will evaluate the conditional className or style and change the appearance of elements to match the dark mode.
You can find more React guides on https://simplefrontend.com/.