19

SCENARIO: I am taking over management of a website where the former web developer has unfortunately spread out many relevant functions over many long JS files. It is hard for me to find where an inline CSS style is coming from in the JS or what function is applying this style directly to the element.

QUESTION: Is there a method of reverse engineering an element's inline styles to see where they are coming from?

JLF
  • 2,280
  • 4
  • 28
  • 45

1 Answers1

35

A possible way is to add a DOM breakpoint in Chrome Dev Tools

enter image description here

For that to work, you have to add the breakpoint before the style is added. That can be tricky, but you can force a breakpoint before loading any JavaScript by adding the following immediately after the HTML element in question

<script>debugger</script>

Try it on the following code

  • Click on the "Run Code Snippet" button below
  • Open Dev Tools
  • Right click the paragraph
  • Select Break On... -> Attribute modifications
  • Click the "Add border color" button
  • Voila, your debugger stops at the code that is modifying the style

window.onload = function() {
    document.querySelector('button').addEventListener('click', function() {
         document.querySelector('p').style.border = '2px solid red';    
    });
}
<p> Sample Paragraph </p>
<button>Add border color</button>
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • Tip: Set a single `Subtree Modifications` DOM breakpoint on a top-level node, like the `body`, and a breakpoint will get triggered whenever any of its children are modified. – Kayce Basques Jan 06 '17 at 20:06
  • @KayceBasques Not sure it's a good idea, you will get flooded with breakpoints. For this question, the OP wants to know specifically when a specific element is about to be modified. Your suggestion may be valid in other contexts but not for this question as asked. From the OP `an inline CSS style is coming from in the JS or what function is applying this style directly to the element.` – Ruan Mendes Jan 06 '17 at 20:23
  • @JuanMendes Right. Depends on the context. It's useful when you don't have a lot of nodes getting modified, though. – Kayce Basques Jan 06 '17 at 20:29
  • But what to do, if the element is 'styled' at the very load of the page? All DOM breakpoints are reset in this case... – Vadim Anisimov Nov 26 '18 at 14:18
  • @VadimAnisimov You didn't read the full answer? `For that to work, you have to add the breakpoint before the style is added. That can be tricky, but you can force a breakpoint before loading any JavaScript by adding the following immediately after the HTML element in question ` – Ruan Mendes Nov 26 '18 at 14:54