Malasorte
Malasorte

Reputation: 1173

Javascript: Change <link rel="stylesheet"> media attribute

If a user visits my website from a desktop computer, in my HTML I call a CSS style like this:

<link rel="stylesheet" type="text/css" href="desktop.css" media="all and (min-device-width:768px)" />

Using plain javascript (no framework) how can I change the media attribute from "all and (min-device-width:768px)" to "all and (min-width:768px)" ?

Thank you!

Upvotes: 1

Views: 2252

Answers (2)

Ionică Bizău
Ionică Bizău

Reputation: 113385

Give it an id and change the attribute value:

<link id="foo" rel="stylesheet" type="text/css" href="desktop.css" media="all and (min-device-width:768px)" />

And the jQuery part:

$("#foo").attr("media", "all and (min-width:768px)");

JSBIN


No jQuery version

document.querySelector("#foo").setAttribute("media", "all and (min-width:768px)");
// or
document.getElementById("foo").setAttribute("media", "all and (min-width:768px)");

Upvotes: 3

Kirill Pisarev
Kirill Pisarev

Reputation: 843

if you don't have access to source code and can't set id for link, first you have to do is to filter links by media attribute. Then just set new attribute value to filtered:

var links = document.getElementsByTagName('link');
for(var i = 0; i < links.length; i++){
    var link = links[i];
    if(link.getAttribute('media') === 'all and (min-device-width:768px)')
        link.setAttribute('media', 'all and (min-width:768px)');
}

fiddle

Upvotes: 1

Related Questions