Search code examples
javascriptjquerydommutation-observers

Implementing MutationObserver in place of DOMSubtreeModified


I have a select[multiple] which I have given a class custom-multiselect on my page for which I am catching the DOMSubtreeModified event as follows:

HTML:

<select class="custom-multiselect"></select>

JQuery:

$('.custom-multiselect').each(function (i, select) {
    var sel = this;
    adjustHeight(sel); //Custom function
    //Binding DOMSubtreeModified to catch if the select list gets modified by the user
    $(sel).on('DOMSubtreeModified', function () {            
        adjustHeight(sel);
    });
    //For Internet Explorer
    $(sel).on('propertychange', function () {
        adjustHeight(sel);
    });
});

This approach works flawlessly. I want to convert the DOMSubtreeModified function into MutationObserver since DOMSubtreeModified is depreciated.

So I did something like this:

var observer = new MutationObserver(function (mutation) {
    mutation.forEach(function (m) {
        if (m.type == 'subtree') {
            adjustHeight(this);//Can I use m.target here?
        }
    });
});
observer.observe(document.querySelector('select.custom-multiselect'), {
    subtree: true
});

But I end up getting error

TypeError: The expression cannot be converted to return the specified type.

How can I convert my DOMSubtreeModified event to be observed by the MutationObserver?


Solution

    • Put the code in place of the old DOM event and use your sel variable as the observation target;
    • Use childList option in MutationObserver because subtree doesn't specify what to look for;
    • There's no need to check the mutations since you subscribe only to one type.

    $('.custom-multiselect').each(function() {
        var sel = this;
        adjustHeight(sel);
    
        new MutationObserver(function() {
            adjustHeight(sel);
        }).observe(sel, {childList: true, subtree: true});
    });
    

    Or, if you like .bind for some reason:

    new MutationObserver(adjustHeight.bind(null, sel))
        .observe(sel, {childList: true, subtree: true});