how to add css to javascript code example

Example 1: add style javascript

// Bad:
element.setAttribute("style", "background-color: red;");
// Good:
element.style.backgroundColor = "red";

Example 2: add css in javascript

document.getElementById("demo").style.display = "none";

Example 3: 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 4: js add css to document

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

Tags:

Css Example