Detecting Div content change

Detecting when the contents of a div changes using MutationObserver

by andysmiffy

HTML

<select id="options" name="options">
    <option name="val1" value="None" >Please select</option>
    <option name="val2" value="John" >John</option>
    <option name="val3" value="Paul" >Paul</option>
    <option name="val4" value="George" >George</option>
    <option name="val5" value="Ringo" >Ringo</option>
</select>
<div id="test">No favourite Beetle chosen</div>
<div id="changed">Div not changed</div>
<div id="error">No Error</div>

JavaScript

$('#options').change(function () {    
    $('#test').text("My favourite Beetle is : " + $(this).val() );    
});

$(document).ready(function () {
    // create an observer instance
    var target = document.querySelector('#test');
    console.log(target);
    var observer = new WebKitMutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            //Update the div to say it has changed
            $('#changed').text("the div changed: " + $(this).val());
        });
    });

    // Configuration of the observer:
    var config = { 
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true
    };
    //Tell it to observe
    observer.observe(target, config);

    if (target === undefined) {
        $('#error').text("target is undefined");
    } else {
        if (target === null) {
            $('#error').text("target is null");
        } else {
            $('#changed').text("Detected div changed: ");

        }
    };

});