css in js file code example

Example 1: javascript add css file

var cssFile = document.createElement('link');
    cssFile.rel = 'stylesheet';
    cssFile.href = "styles.css";  // or path for file {themes('/styles/mobile.css')}
    document.head.appendChild(cssFile); // append css to head element

Example 2: append css file with javascript

var cssFile = document.createElement('link');
    cssLink1.rel = 'stylesheet';
    cssLink1.href = "styles.css";  // or path for file {themes('/styles/mobile.css')}
    document.head.appendChild(cssFile); // append css to head element

Example 3: html css and js in one file

<html>
    <head>
        <style type="text/css">
            CSS goes here
        </style>
        <script type="text/javascript">
            JS goes here
        </script>
    </head>

    <body>
        HTML goes here
    </body>
</html>

Example 4: js add css to document

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';

Tags:

Misc Example