-1

I am trying to console log every changes i make in google developer tools

<div class="test">2</div>
var result = document.getElementsByClassName("test")[0].innerHTML;
console.log(result);

So i have a number 2 inside a div, and it prints out 2 in console, but when i edit this div using google developer tools for example to 3, the console log never prints out new changes i make.

Jquery or javascript?

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
Moodland
  • 132
  • 5
  • how it's supposed to know that you made a change ? you need to have an event listener attached to it in order to make it work – Noob Oct 03 '19 at 15:31
  • FYI: `document.getElementsByClassName("test")[0].innerHTML` is just an awful line of code. Don't use `innerHTML` when you're not getting/setting any actual HTML and [don't use `getElementsByClassName()` at all, much less adding an index to it.](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) – Scott Marcus Oct 03 '19 at 15:35

1 Answers1

2

Nothing is going to re-run your console.log line for you unless you tell it to.

In this case, the thing you'd use to tell it to is a MutationObserver. You'd say you want to see all mutations (modifications) to that element's character data, child list, and subtree (most likely).

For example, if you use devtools to change the foo in this example, you'll get a notification of that change:

const target = document.querySelector(".test");

const observer = new MutationObserver(function() {
    console.log(target.innerHTML);
});

observer.observe(target, {
    characterData: true,
    childList: true,
    subtree: true
});
<div class="test">foo</div>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875