Load Css string at Runtime JS

by Pratik Bhoir

HTML

<button onClick="loadCss();">Load Css</button>
<div>Text</div>

JavaScript

function loadCss() {
    var cssText = "div { background-color: black; color: white;} button{color:red;}";
    var css = document.createElement("style");
    css.type = "text/css";
    if ("textContent" in css) css.textContent = cssText;
    else css.innerText = cssText;
    document.body.appendChild(css);
}