乐闻世界logo
搜索文章和话题

How to create a < style > tag with Javascript?

1个答案

1

Creating a

  1. Create a : First, use the document.createElement method to create a new

  2. Set the style content: Then, utilize the textContent property or the appendChild method combined with createTextNode to define CSS rules.

  3. Insert the : Finally, employ the document.head.appendChild method to add the newly created

Here is a specific implementation:

javascript
// Create a new style element var style = document.createElement('style'); // Set CSS rules // Example: Apply background color and font color to the body style.textContent = `\n body {\n background-color: #f3f3f3;\n color: #333;\n }\n`; // Insert the style element into the head document.head.appendChild(style);

In this example, I configured the page background color and font color. Naturally, you can incorporate any CSS rules as required. This technique enables dynamic control over page styles and can be leveraged to adjust styles based on user interactions or other events.

2024年6月29日 12:07 回复

你的答案