Javascript Style How to - Create style element and append to body element








Question

We would like to know how to create style element and append to body element.

Answer


<!DOCTYPE html>
<html>
<body>
<script type='text/javascript'>
<!--from   w w w  . j  av a2  s.c  o m-->
    var styleElement = document.createElement("style");
    styleElement.innerHTML = "body { \n\
                background: red; \n\
            }";
    document.body.appendChild(styleElement);

</script>

</body>
</html>

The code above is rendered as follows: