Search code examples
cssdomstylesheet

Reading class names in a stylesheet


I have an HTML document that uses multiple style tags. One of those styles has the following content

<style id='pstyle'>
.p0010, .p0016, .p0022, .p0028, .p0032, 
.p0034, .p0038, .p0042, .p0044, .p0046, 
.p0048, .p0050, .p0052, .p0054, .p0056, 
{
 max-width:100%; 
 background-size:100%; 
 background-image: url('sprites.png');
}
</style>

document.styleSheets allows me to access the full set of stylesheets used by the document. From there - once I have grabbed the right stylesheet - I can use the cssRules array attribute to access the selectorText attribute of each contained style. However, I have been unable to figure out how to find the "right" style sheet. Whilst I can give the stylesheet an id this does not turn up as an attribute of the document.styleSheets[n] object.

I do a great deal of DOM manipulation but it is mostly with the visual elements in the document. I'd be much obliged to anyone who can tell me how I go about identifying the "right" stylesheet


A plain English version of the task

a. Find the style element - bearing in mind that there will be others - with the id pstyle b. Read the class names defined therein and do whatever


Solution

  • I'm not sure to understand if you want to get the stylesheet associated with the <style> element, or if you want to retrieve the element from the stylesheet.

    So here you'll get both :

    // from the element
    console.log(pstyle.sheet === document.styleSheets[2]);
    // from the stylesheet
    console.log(document.styleSheets[2].ownerNode === pstyle);
    <style id='pstyle'>
    </style>

    note that in the snippet it's [2] because stacksnippet does inject stylesheets

    And now to get the cssRules and selectorText, you just have to read it from the selected styleSheet:

    var pstyle = document.getElementById('pstyle');
    
    // from the element
    console.log(pstyle.sheet.cssRules[0].selectorText);
    
    // from the stylesheets
    for(var sheet of document.styleSheets){
      if(sheet.ownerNode === pstyle){
        console.log(sheet.cssRules[0].selectorText);
        }
      }
    <style id='pstyle'>
    .p0010, .p0016, .p0022, .p0028, .p0032, 
    .p0034, .p0038, .p0042, .p0044, .p0046, 
    .p0048, .p0050, .p0052, .p0054, .p0056 
    {
     max-width:100%; 
     background-size:100%; 
     background-image: url('sprites.png');
    }
    </style>