I know how to use JS to add a stylesheet to an HTML document:
// given CSS as text, add a <style> to the document
function addStyle(css) {
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
}
How do I create a checkbox that can toggle this (and only this) stylesheet on and off?
This answer gives hints about how to manipulate stylesheets in JS, but there does not appear to be a way of locating a specific stylesheet without looping through document.styleSheets
and matching against document.styleSheets[i].cssRules[j].cssText
, which seems unwieldy.
Is there a better way to do this, ideally without jQuery, than a double loop?
(My particular use case is for a userscript (e.g. Greasemonkey), though I avoid GM_addStyle
for portability. All this really means is that I don't have direct control over the HTML; I'm modifying other sites.)