HTMLInputElement's .value can't be watched with Mutation Observers

556 views Asked by At

Codepen here.

HTML:

<input placeholder="HRM"/>

JavaScript:

let input = document.querySelector('input')

let observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'attributes') {
      //let value = mutation.target.value
      console.log(mutation)
      console.log(mutation.attributeName)
    }
  })
}).observe(input, {
  attributes: true
})

input.placeholder = 'asdfsd'
input.value = "Y U NO FIRE"

When the placeholder attribute is changed, the Mutation Observer fires. But when the value attribute is changed, the Mutation Observer does not fire. Does anyone have solid understanding of why? (Hopefully backed with a link to the ECMAScript/HTML5 standards.)

Does anyone know how we can watch for when JavaScript makes changes to HTMLInputElement's value via input.value?

1

There are 1 answers

0
Mario Andrade On

The Mutation Observer will observe changes in the DOM but when you type text inside an input, if you inspect the DOM element, there is not change. So we need to trigger that change.

You can do that by setting the input attribute to the inserted value. See the code bellow.

let input = document.getElementById('inp');
let result = document.getElementById("result");

let observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'attributes') {
      result.innerHTML = mutation.target[mutation.attributeName];
    }
  })
}).observe(input, {
  attributes: true
});

input.oninput = () => {
  input.setAttribute("value", input.value);
}
<input placeholder="HRM" value="" id="inp" />

<p>Mutation observer result:<br />
  <div id="result"></div>
</p>