9

I want to detect changes in div-elements. I tried already the "addEventListener" with some types (e.g.: change, load).

Here is my example, but the event won't trigger:

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <div id='DivElement'>Test Div Text...</div>
        <button type="button" onclick="EditDivElement()">click me!</button>

        <script>
            function EditDivElement() {
                ClickCounter++;
                SelectedDiv.textContent="new text content: " + ClickCounter;
            }

            function OnDivEdit() {
                alert("success!");
            }

            var ClickCounter = 0;
            var SelectedDiv = document.querySelector("#DivElement");

            SelectedDiv.addEventListener("change", OnDivEdit);
        </script>
    </body>
</html>

(Edit: It's for a browser-addon and it should be used on other websites.)

Flo93atx
  • 93
  • 1
  • 1
  • 5
  • 1
    As you're the one making the changes, you should just hook into the functions you already have, as listening for DOM changes (mutations) is usually not a very good idea. – adeneo Apr 11 '16 at 23:39
  • It's for a browser-addon and it should used on other websites. – Flo93atx Apr 11 '16 at 23:42
  • maybe this? http://stackoverflow.com/questions/15657686/jquery-event-detect-changes-to-the-html-text-of-a-div – Ronnie Apr 11 '16 at 23:46

1 Answers1

21

You can use a MutationObserver.

From MDN:

// 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();

Note: Deprecated

What I have done in the extensions I wrote was to listen on DOMNodeInserted.

div.addEventListener("DOMNodeInserted", function (e) {
    e.target // 
}, false);
BrunoLM
  • 97,872
  • 84
  • 296
  • 452