Search code examples
javascriptmutation-observers

Mutation observer event new value


I am learning to use the Mutation observer class, mostly here: https://javascript.info/mutation-observer

I know how to listen to changes of attributes, and how to get old attribute values using attributeOldValue. But can I get the new attribute value from the same event? If so, how? Thanks


Solution

  • You can simply query current value directly from the changed object.

    // is element is an input
    const newValue = document.getElementByID('myElement').value;
    
    
    // or, if it is a any text element
    const newValue = document.getElementByID('myElement').innerHTML;
    
    

    Also, each MutationRecord have a property named target which contains all detailed information about changed object. So depending on MutationRecord.type (which tells us what type of the change have happened) you can get new value from corresponding property inside MutationRecord.target