user2461391 user2461391 - 4 years ago 159
CSS Question

Changing the stylesheet in a div with a chrome extension

Using a chrome extension, I want to change the stylesheet associated with an individual div.

For example, the current page looks like:

<div id="footer">
<link rel="stylesheet" type="text/css" href="linktostylesheet.css">

I would like to not use the that stylesheet, and insert my own:

<div id="footer">
<link rel="stylesheet" type="text/css" href="link to my new stylesheet.css">

I am a little lost with this type of programming. So far I have the following snippet of code in my content script, however I don't think I have the right idea.

d = document.getElementById("footer").getContentDocument();
d.styleSheets[d.styleSheets.length].href = 'newstylesheet.css';

Answer Source

<link> element should be child of <head> element. You can select the link element by beginning value of href attribute, set href of element to new value.

document.querySelector("link[href^=linktostylesheet]").href = "newstylesheet.css";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download