检测javascript中的div变化

For*_*bit 2 html javascript dom detection

我正在开发一个有趣的小 chrome 扩展,我需要它能够做的一件事是检测 div 内的文本何时被网页本身更改。我使用的代码是:

var status = document.getElementById("status").innerHTML;
status.onchange = function() {
    console.log("CHANGE DETECTED")
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用,那么我应该使用什么?

注意:我不想使用 jquery,因为我目前对 javascript 还不是很精通,但如果它会更简单/更容易,那就没问题了。

小智 7

使用这个技巧

来源:https : //hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/

// select the target node
    var target = document.querySelector('#some-id');

    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation.type);
        });
    });

    // configuration of the observer:
    var config = { attributes: true, childList: true, characterData: true }

    // pass in the target node, as well as the observer options
    observer.observe(target, config);

    // later, you can stop observing
    observer.disconnect();
Run Code Online (Sandbox Code Playgroud)