Languages
[Edit]
EN

JavaScript - how to create <style> tag?

10 points
Created by:
Kate_C
2952

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, 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 poperty 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>

 

Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.