Search code examples
cssstylesheet

how to get a CSSStyleSheet object from a <style>


One < style > corresponding one CSSStyleSheet object (in document.styleSheets), but how to find it, such as the CSSStyleSheet object corresponding < style id="-yCoder-styles" >...< /style>

console.log(document.styleSheets.length);

var style = document.createElement('style');
style.title = "-yCoder-styles";
style.type= 'text/css';
style.id = "-yCoder-styles";
document.head.appendChild(style);

//how to get the corresponding CSSStyleSheet instance from document.styleSheets

console.log(document.styleSheets.length);

var styleSheet = document.styleSheets[document.styleSheets.length - 1];
console.log(styleSheet.title == style.title);

Solution

  • Based on the code you provided, you should be able to get your associated CSSStyleSheet with:

    var styleSheet = style.sheet
    

    This will only work after the <style> element has been appended to the document.

    Not exceptionally well documented and very difficult to find by poking around in console.