Créer un site internet

Inject CSS with javascript in html page

fredericdietrich By On 30/10/2023

In HTML

How to inject css in your page with javascript

 


// The content of the stylesheet
const styleSheetContent = `
    .demo{
        background:red;
        color: yellow;
    }

    .demo2 {
        font-size: 1.2rem;
        color: black;
    }
`;

// Creates the style element
function createStyleElement(id, content) {
    var style = document.createElement("style");
    style.type = "text/css";
    style.id = id;
    style.innerHTML = content;

    if (style.styleSheet) {
        style.styleSheet.cssText = content;
    } else {
        let st = document.getElementById(id);
        if(st == undefined){
            var head = document.head || document.getElementsByTagName("head")[0];
            head.appendChild(style);
        } else {
            st.innerHTML = content;
        }
    }
    return style;
}

createStyleElement("fdiStyle", styleSheetContent);

 

 

javascript

  • No ratings yet - be the first to rate this.