skip to Main Content

My question is if there is a way to access the content of HTML <style> element from jQuery.

<style>
.calendarNavbarLink {
    margin-left: 20px;
}

.today {
    background-color: lawngreen;
}

.weekend {
    background-color: lightsalmon;
}
</style>

For example: I would access the value of the property background-color of the rule .weekend. Is it possible do this from jQuery?

2

Answers


  1. Use styleSheets property of JS to get the styleSheets content.

    const styleSheet = document.styleSheets[0].cssRules
    

    After this, you can loop through the classes, to get the desired result.

    Refer:- https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets

    Login or Signup to reply.
  2. Step 1:

    By using a couple of CSSOM (CSS Object Model) properties, you can query your stylesheet and build an easy-to-search array of selectors and style rules:

    // GET ALL STYLESHEETS
    let styleSheetCount = document.styleSheets.length;
    
    // GET LAST STYLESHEET
    let lastStyleSheet = document.styleSheets[(styleSheetCount - 1)];
    
    // CONVERT STYLESHEET TO OBJECT
    const convertStylesheetToObject = (stylesheet) => {
      
      // CREATE AND POPULATE STYLE ARRAY
      let styleArray = [];
      [...stylesheet.cssRules].forEach((cssRule) => styleArray.push(cssRule.cssText));
    
      styleArray = styleArray.map((style) => ({
        'selector': style.split('{')[0].split(',').map((selector) => selector.trim()),
        'styles': style.split('{')[1].replace('}', '').trim()
      }));
    
      styleArray.forEach((style) => style.styles = style.styles.split(';'));
      
      styleArray.forEach((style, s) => {
        let stylesValue = {};
        styleArray[s].styles.forEach((styleDeclaration) => {
          if (styleDeclaration !== '') {
            stylesValue[styleDeclaration.split(':')[0].trim()] = styleDeclaration.split(':')[1].trim();
          }
        });
        styleArray[s].styles = stylesValue;
      });
      
      return styleArray;
    }  
    
    console.log(convertStylesheetToObject(lastStyleSheet));
    <style>
    .calendarNavbarLink {
      margin-left: 20px;
    }
    
    .today {
      background-color: lawngreen;
    }
    
    .weekend {
      background-color: lightsalmon;
    }
    </style>

    Having done this, if you now run:

    convertStylesheetToObject(lastStyleSheet)
    

    you will get the following array:

    [
      {
        "selector": [
          ".calendarNavbarLink"
        ],
        "styles": {
          "margin-left": "20px"
        }
      },
      {
        "selector": [
          ".today"
        ],
        "styles": {
          "background-color": "lawngreen"
        }
      },
      {
        "selector": [
          ".weekend"
        ],
        "styles": {
          "background-color": "lightsalmon"
        }
      }
    ]
    

    Step 2:

    You now have an array you can parse with a helper function.

    E.g. If you want to know

    […] the value of the property background-color of the rule .weekend.

    you can run:

    getStyleValue('.weekend', 'background-color', styleArray)
    

    which returns the following result:

    const getStyleValue = (selector, property, styleArray) => {
      
      let styleValue = 'No value found.';
      
      const selectorFilter = styleArray.filter((element) => element.selector.includes(selector));
      
      if (selectorFilter.length > 0) {
        const propertyFilter = selectorFilter.filter((element) => Object.keys(element.styles).includes(property));
        if (propertyFilter.length > 0) {
          styleValue = propertyFilter.reverse()[0].styles[property];
        }
      }
      
      return styleValue;
    }
    
    let styleArray = [
      {
        "selector": [
          ".calendarNavbarLink"
        ],
        "styles": {
          "margin-left": "20px"
        }
      },
      {
        "selector": [
          ".today"
        ],
        "styles": {
          "background-color": "lawngreen"
        }
      },
      {
        "selector": [
          ".weekend"
        ],
        "styles": {
          "background-color": "lightsalmon"
        }
      }
    ];
    
    console.log(getStyleValue('.weekend', 'background-color', styleArray));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search