Pavel Horyna
Pavel Horyna

Reputation: 431

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

Upvotes: 2

Views: 3038

Answers (2)

vikjaros
vikjaros

Reputation: 1

We can listen for mutations and take content from the target where it has already happened. (the example is not on your topic, but the principle is similar)

document.addEventListener('DOMContentLoaded', function () {
  let targetEl = document.querySelector('body');

  function checkChange(mutations, observer) {
     //****************************
     console.log(mutations[0].target.innerHTML);
     //****************************
  }

  let observer = new MutationObserver(checkChange);

  observer.observe(targetEl, {
     subtree: true,
     childList: true,
     characterData: true,
     characterDataOldValue: true,
  })

})

Upvotes: 0

Denis O.
Denis O.

Reputation: 1850

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

Upvotes: 3

Related Questions