Home > Article > Web Front-end > How Can I Add CSS Styles Dynamically Using JavaScript?
JavaScript offers a robust mechanism for dynamically adding CSS rules to a document. This functionality empowers developers to alter the visual appearance of their web pages without having to modify the HTML markup.
The most straightforward approach is to create a new style node and append it to the document's head:
<code class="javascript">// Define your custom CSS as text var styles = ` .my-class { color: red; font-weight: bold; } `; // Create a new style element and set its text content var styleSheet = document.createElement("style"); styleSheet.textContent = styles; // Append the style element to the document head document.head.appendChild(styleSheet);</code>
With this approach, your custom CSS rules will be applied to the document, dynamically enhancing its visual presentation.
The above is the detailed content of How Can I Add CSS Styles Dynamically Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!