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...

arnaudambro
  • 2,403
  • 3
  • 25
  • 51
  • [This article](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information) should be helpful for you, I think – Flying Oct 19 '17 at 10:53
  • Also [this example](https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList#Example) seems to be related to your question – Flying Oct 19 '17 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. – CBroe Oct 19 '17 at 11:09

1 Answers1

2

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);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875