Search code examples
javascriptcsshead

How to target CSS link with JavaScript


I only have access to the back end of my CMS. They are loading the custom style sheet this way

<link rel="stylesheet" media="(min-width:481px)" href=".../css/custom/styles.css" type="text/css">

I need to remove the media="(min-width:481px)". Is there a way to do this with JavaScript (I don't think the CMS uses jquery)?


Solution

  • I personally do not recommend messing with the elements of a link with JavaScript, but if you still want to do it, this should work:

    document.querySelector('link[href=href=".../css/custom/styles.css"]').removeAttribute('media');
    

    If you still want to do this, make sure to wait for css styles to load.

    If you want to go with this solution for some reason and do it for all link tags, then this one is simple:

    var linkList = document.querySelectorAll('link');
    
    for(var i in linkList) {
    linkList[i].removeAttribute('media');
    }
    

    Always use .removeAttribute, instead of using setAttribute to set the argument to null. That is generally bad practice.