08 March 2016

Add or remove a CSS stylesheet to HTML using plain vanilla Javascript

This little function will attach or delete a new stylesheet to your html page using good old JS. The second parameter is optional so it will toggle on or off the stylesheet, depending on it's current setting. The function will return true or false (1 or 0), depending on weather the style is on or off. Enjoy!


function toggleStylesheet(href,onoff){
    var existingNode=0 //get existing node:
    for(var i = 0; i < document.styleSheets.length; i++){
        if( document.styleSheets[i].href && document.styleSheets[i].href.indexOf(href)>-1 ) existingNode = document.styleSheets[i].ownerNode
    }
    if(onoff == undefined) onoff = !existingNode //toggle on or off if undefined
    if(onoff){ //TURN ON:
        if(existingNode) return onoff
        var link  = document.createElement('link');
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.href = href;
        document.getElementsByTagName('head')[0].appendChild(link);
    }else{ //TURN OFF:
        if(existingNode) existingNode.parentNode.removeChild(existingNode)
    }
    return onoff
}

//EXAMPLES:

toggleStylesheet('myStyle.css') //toggle myStyle.css on or off

toggleStylesheet('myStyle.css',1) //add myStyle.css

toggleStylesheet('myStyle.css',0) //remove myStyle.css

Cron Design Studio: Dublin based web design & software development