2

Because I am quite new to programming and I am discovering Bootstrap right now, I am doing an exercise with containers and rows and col-XX etc., to know how what are their CSS properties.

Therefore, I am looking for getting the CSS values that devs put in the CSS files with Javascript. Not jQuery, but vanilla JS. Not the CSS values computed, but the CSS values written. Like the one we have in the console. I want to get them in order to put them back in a the HTML this way : <p>margin-right: 5%</p>, for example.

So a lot of people are talking about window.getComputed(element).getPropertyValue("property"), but I am not interested. I heard somewhere cssText, but I am not sure that it's the good one.

Is there a solution ? Is there actually a place somewhere where all the property-values-written of a selector are stored, in parallel to the property-values-computed ?

Thanks Arnaud

PS: I know the subject is already open there but it opened 7 years ago, and the only self-answer is not satisfying I think...

3
  • This article should be helpful for you, I think Commented Oct 19, 2017 at 10:53
  • Also this example seems to be related to your question Commented Oct 19, 2017 at 10:58
  • "to know how what are their CSS properties. [...] Therefore, I am looking for getting the CSS values that devs put in the CSS files with Javascript. " - for the stated purpose, I'd much rather recommend you familiarize yourself with your browser's dev tools, because they have all the info you could possible be looking for available already - and have the advantage that you can inspect everything "live" with just a few clicks. You won't have to figure out how to get to the elements of interest via JavaScript, etc. pp. - they're all literally "at your fingertips" already. Commented Oct 19, 2017 at 11:09

1 Answer 1

3

If you need to access this information programmatically (as opposed to just looking at it in devtools), you're looking for the document.styleSheets collection. Each stylesheet in the collection has the CSS rules and media query rules, etc., for that stylesheet, in a form where you can access the actual style info, not the computed result.

For example:

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
forEach(document.styleSheets, function(sheet, index) {
  forEach(sheet.cssRules || sheet.rules, function(rule) {
    if (rule instanceof CSSStyleRule && rule.selectorText == ".foo") {
      console.log(".foo's width rule: " + rule.style.width);
    }
  });
});
.foo {
  width: calc(100% - 10px);
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.