How to delete mutation record objects in javascript

1.3k views Asked by At

I'm observing changes on a Div element, that is being filled with child div's with ajax calls. My aim is to make some checks within the observed Record objects and filter some of them. How can i delete/remove/filter these mutation records from the observed mutation list? and make them filtered in the web page.

I tried to remove the mutation record from the mutations list but it didn't work. Thanks for your help.

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        var addedNode = mutation.addedNodes[0];
        if(addedNode){
            var innText = addedNode.innerText;
            //console.log("number " + i + " | " + addedNode.innerText);
            if(innText){
                if(innText.toLowerCase().indexOf(someText) > -1){
                    mutations.remove(mutation);
                }
            }
        }
    });

});

var config = {
    attributes: true,
    childList: true,
    characterData: true,
    characterDataOldValue: true,
    subtree: true
};
observer.observe(text, config);
2

There are 2 answers

1
Fer To On

I assume that your mutation object is a complex one and not a plain data type, therefore your "indexOf" check in your .remove Method will not remove anything.

You should create an additional method, like "checkForElement" or something. In that method you can decide what is equality for your mutation objects.

There are already solutions for that at Stack Overflow, e.g. indexOf method in an object array?

2
Amit On

You can't abort the mutations since when the callback is executed, the mutation already occured.

What you can do instead is "rollback" the mutation using the information provided in the MutationRecord, particularly the addedNodes which you seem to care for. You could simple iterate these, and for each node remove it from it's parent:

if(node.parentNode) {
  node.parentNode.removeChild(node);
}