EN
JavaScript - create style tag
10
points
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:
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>