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

12 comments:

  1. This is a wonderful article, obat aborsi cytotec asli Given so much info in it, These type of articles keeps the users obat aborsi surabaya interest in the website, and keep on sharing more ... good luck cara menggugurkan kehamilan.

    ReplyDelete
  2. Thank you for this wonderful post. It is very informative and useful. I would like to share something here too.carpet steam cleaning

    ReplyDelete
  3. It is quite helpful that you have offered this information on your blog. We sincerely appreciate the effort you put into your article, and it helps us, too. Thank you for sharing this information.cms development

    ReplyDelete
  4. The fact that you provided this knowledge on your blog is quite beneficial. We genuinely appreciate the time and work you put into writing your article, which also benefits us. I appreciate you giving this knowledge.web development services

    ReplyDelete
  5. You have given me a very complete post about. I and those who like it think it's a fantastic piece. Your sharing of this information with us is greatly appreciated.electronic signature

    ReplyDelete
  6. Your post was interesting and effective. Good luck with your upcoming updates!
    cheese stores

    ReplyDelete