2

I want to get the element computed style and the css (file and line) that applies that rule. Similar to what Chrome Dev Tools does when the "Computed" tab is used and you click on that arrow beside the value.

In short, I want to be able to, using javascript, find out these two things:

  1. What is the CSS value that is actually being applied to that element (computed style)
  2. Once I found the computed style, I want to know where it comes from (like file name and line number)

I know this can be done manually using devtools, but I need this done by a script.

Thanks

  • [look at this, it seems to answer your question](http://stackoverflow.com/questions/2952667/find-all-css-rules-that-apply-to-an-element) – qwasyx May 18 '17 at 19:12
  • 1
    It solves my first problem, but not the second item: (Once I found the computed style, I want to know where it comes from (like file name and line number)). – Felipe Silva May 18 '17 at 19:47
  • As this question is locked, I put an answer to the 2nd question in the linked question: https://stackoverflow.com/a/67287941/885872 – Puggan Se Apr 27 '21 at 17:30

1 Answers1

0

You can use Window.getComputedStyle(). An example of usage:

<style>
 #elem-container{
   position: absolute;
   left:     100px;
   top:      200px;
   height:   100px;
 }
</style>

<div id="elem-container">dummy</div>
<div id="output"></div>  

<script>
  function getTheStyle(){
    var elem = document.getElementById("elem-container");
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = theCSSprop;
   }
  getTheStyle();
</script>

See MDN Documentation to learn more how to use this feature and it's compatibility with different browsers.

Unfortunately, this approach will not give you the location of where this value comes from.

achref
  • 1,150
  • 1
  • 12
  • 28
  • achref, thankd for the answer. I found this solution before asking it here but unfortunately I need the location in the CSS file that defines it... – Felipe Silva May 18 '17 at 19:46