Home > Article > Web Front-end > How to Dynamically Modify CSS Class Styles in JavaScript without getElementById?
Modifying CSS Class Styles in JavaScript without getElementById
Problem:
How to dynamically modify the CSS styles of an element by targeting a class in JavaScript without using getElementById?
Answer:
While it is possible to modify CSS styles using the styleSheets array in JavaScript, a more efficient alternative is to create separate styles with the desired display settings.
For example, create a style sheet with the following rule:
.hidden { display: none; }
To apply this style to an element, use the remove() method:
const element = document.querySelector(".hidden"); element.classList.remove("hidden");
This removes the hidden class and its style rules, making the element visible.
Additional Note:
It's important to note that this approach creates new style rules in the DOM. While it provides more flexibility and control over styling, excessive use of this method can bloat the document's memory usage.
The above is the detailed content of How to Dynamically Modify CSS Class Styles in JavaScript without getElementById?. For more information, please follow other related articles on the PHP Chinese website!