How to monitor element changes on a UL element in

2019-08-28 20:11发布

问题:

I want to monitor a UL element for the changes in child elements such as li added or removed etc. The UL is used to display tabs in the screen where each li will be a separate tab. I don't have control to modify the tab script to call my own functions in my script file when the tabs are changed.

I have to support IE browser mainly for this and have to do it using pure JavaScript.

回答1:

The only way i know for this to be possible would be like this. I cannot say that this is a very good way to do it though.

var onchange = function(element, callback) {
    var HTML = element.innerHTML;
    window.setInterval(function() {
        var newHTML = element.innerHTML;
        if(HTML !== newHTML) {
            HTML = newHTML;
            callback(element);
        }
    });
}

This will monitor the element and check the innerHTML if it has changed it will call your callback function.

Demo: http://jsfiddle.net/qmB97/

Usage:

onchange(HTMLElement, function() {
   alert('change');
});


回答2:

IE11 should support MutationObserver