Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Removing media query from external css file

How could I remove media query loaded from external css file (<link rel="stylesheet" type="text/css" href="XXXX.css" media="screen">)? Note that I cant disable the entire link tag because other important styles are included out of that media query:

body{...}
.container{...}
...
@media(min-width:XXXpx) {
....
}
...

Thank you!

like image 262
farrusete Avatar asked Oct 30 '25 03:10

farrusete


1 Answers

I strongly recommend pure CSS solution for this problem, such as defining a new stylesheet overwritting rules you don't want.

#selector {
    color: #000;
}

.some-classs-you-want-to-reserve {/*..*/}

@media only screen and (min-width: 600px) {
    /* unwanted */
    #selector {
        display: none;
    }
}

For example, if you want to mute rules inside @media only screen and (min-width: 600px), simply add a new stylesheet overwritting them to default values:

@media only screen and (min-width: 600px) {
    /* unwanted */
    #selector {
        display: block;
    }
}

If you insist on using Javascript, you can access and modify css rules by iterating document.styleSheets.

document.styleSheets

  • https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList
  • https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets

This is an instance of StyleSheetList, an array-like object. Each item of it represents an external or inline css stylesheet. All rules including media queries can be found inside it.

A brief tree structure:

- document.styleSheets
   |- CSSStyleSheet
       |- cssRules
       |- media

So here's an example showing how to remove all rules defined inside @media only screen and (min-width: 600px) block:

function removeRule() {
    if(typeof window.CSSMediaRule !== "function") 
        return false; //Your browser doesn't support media query feature

    var s = document.styleSheets, r,
        i, j, k;

    if(!s) return false; //no style sheets found

    // walk throuth css sheets
    for(i=0; i<s.length; i++) {
        // get all rules
        r = s[i].cssRules; 
        if(!r) continue;

        for(j=0; j<r.length; j++) {
            //If there's a rule for media query
            if(r[j] instanceof CSSMediaRule &&
                    r[j].media.mediaText == "only screen and (min-width: 600px)") {
                for(k=0; k<r[j].cssRules.length; k++) {
                    // remove all rules of it
                    r[j].deleteRule(r[j].cssRules[k]);
                }
                return true;
            }
        }
    }
}
removeRule();

Or live fiddle: http://jsfiddle.net/e4h41qm2/


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!