Explain Codes LogoExplain Codes Logo

How to create a <style> tag with Javascript?

javascript
browser-compatibility
dynamic-styles
css-rules
Nikita BarsukovbyNikita Barsukov·Nov 7, 2024
TLDR

By using the JavaScript method document.createElement('style'), you can generate a <style> tag. After creating the tag, you can add your CSS with textContent and then append it to document.head. Here is the code:

let style = document.createElement('style'); style.textContent = `body { background: #f0f0f0; } .highlight { color: red; }`; document.head.appendChild(style);

This small script injects your custom styles directly into the page, applying them instantly.

Managing browser compatibility

While crafting a <style> tag using JavaScript, it's essential to handle browser compatibility. Most modern browsers can handle the textContent method. However, older versions like IE8 and below have a different process. They use style.styleSheet.cssText to set the styles:

if (style.styleSheet) { // Hello IE8, here’s your drink 🍸 style.styleSheet.cssText = css; } else { // For classy folks 🍷 style.appendChild(document.createTextNode(css)); }

It’s crucial to test your solution across different browsers for universal functionality. While Google Chrome remains a priority, ensure your solution functions well in major players like Firefox, Safari, and Edge.

Dynamically adding and removing CSS rules

For a more dynamic style, you will likely want to add or remove CSS rules on the spot. You can do this by directly manipulating CSS rules via the document.styleSheets:

// Green rules everything around 🍏 document.styleSheets[0].insertRule('p { color: green; }', 0); // When you don’t like green no more 🚫 document.styleSheets[0].deleteRule(0);

Be aware that different browsers have different quirks. For example, IE prefers to use addRule() and removeRule(). In these scenarios, a helper function could be used to smoothen the differences between browsers.

Utilizing jQuery for simplified process

If jQuery is already part of your project, save time and reduce boilerplate code with its cross-browser method to append your <style>:

$("<style type='text/css'> .myStyle { color: #000;} </style>").appendTo("head");

Though it’s not necessary for basic style injections, jQuery can simplify your process and reduce code complexity. But beware, it adds overhead to your page.

Safeguarding with textContent

It's crucial to use .textContent over .innerHTML when adding your styles as it's secure and faster, keeping the threat of XSS (Cross-Site Scripting) vulnerabilities at bay:

style.textContent = yourCssCode;

Employing this method will ensure compatibility across all A-grade browsers, expanding your audience reach without sacrificing performance or security.

Abiding by standard practice

Adhering to standard practices is necessary when creating elements dynamically. Always append your created <style> or <link> elements to document.head:

document.head.appendChild(styleSheet);

This maintains conventional markup structure and ensures consistent behavior across different browsing environments.

Aesthetic and performance consideration

Our code can impact the aesthetics of our webpage as much as its functionality. To avoid FOUC (Flash of Unstyled Content), integrate dynamic <style> creation cleanly into your webpage. This maintains a seamless user experience by injecting styles as part of the initial page load or on user interaction.