Languages
[Edit]
EN

JavaScript - create style tag

10 points
Created by:
Kadeem-Craig
516

In Web Browser JavaScript it is possible to create <style> tag with built-in DOM API.

Quick solution:

var style = document.createElement('style');

style.innerText = 'body { background: red; }' +
                  'p { color: blue; }';
    
document.head.appendChild(style);

Screenshot: 

JavaScript style tag example.
JavaScript style tag example.

There are different ways how to do it:

1. Text child node example

In this section, the example shows how to add new CSS rules with text nodes.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <p>This is red web page...</p>
  <script>
  
    var element = document.createElement('style');

    element.appendChild(document.createTextNode('body { background: red; }'));
    element.appendChild(document.createTextNode('body p { background: yellow; color: blue; }'));
    // appending another rules

    document.head.appendChild(element);

  </script>
</body>
</html>

2. innerText property example

It is possible to assign all styles using one assignment of innerText property.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <p>This is red web page...</p>
  <script>
  
    var element = document.createElement('style');

    element.innerText = 'body { background: red; }' +
                        'body p { background: yellow; color: blue; }';
    
    document.head.appendChild(element);

  </script>
</body>
</html>

Alternative titles

  1. Add style tag from JavaScript
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join