search

Home  >  Q&A  >  body text

I can't access CSS styles in document.styleSheets.cssRules

I'm trying to write this function in javascript to dynamically rearrange a specific object class under a specific parent element. However, I'm having trouble handling certain variables.

const styleSheet = Array.from(document.styleSheets[0].cssRules);
 //filter to create list that contains only "cartelle" class rulesets 
const myRules = styleSheet.filter(ruleset => ruleset.selectorText.includes("cartelle"))

 //iterate along each ruleset in the list
let cardSetLength = Object.keys(myRules).length;
console.log(cardSetLength);
for (let i = 0; i < cardSetLength; i++) {
  //obtain value of the following properties in given ruleset
  let newGridColumn = myRules[i][`grid-row-start`];
  let newGridRow = myRules[i][`grid-column-start`];
  console.log(newGridColumn);
  console.log(newGridRow);
}
.cartelle {
  grid-row-start: 42;
  grid-column-start: 69;
}

In this case, the console logs for both newGridColumn and newGridRow return "undefined", I'm not sure why. The console log for cardSetlength returns a list of 20 dictionaries, each representing a ruleset, but each dictionary is empty, I'm not sure if this has to do with some display convention in the console log, or if My error is related. Any idea what I'm doing wrong here?

P粉637866931P粉637866931504 days ago526

reply all(1)I'll reply

  • P粉462328904

    P粉4623289042023-09-09 09:16:47

    You should access CSS property values ​​from the style field of CSSRule.

    console.log(document.styleSheets[0].cssRules[0].backgroundColor); // undefined
    console.log(document.styleSheets[0].cssRules[0].style.backgroundColor);
    .class {
      background-color: blue;
    }

    Your code should look like this:

    for (const rule of myRules) {
        let newGridColumn = rule.style[`grid-row-start`];
        let newGridRow = rule.style[`grid-column-start`];
        // ...
    }
    

    Note that you can use camelCase for CSS properties in JavaScript instead of bracket notation.

    reply
    0
  • Cancelreply