Javascript Eventlistener for Update / Change on Element / innerText

不羁的心 提交于 2019-12-05 12:10:17

Check out the MutationObserver. Using it you can listen to changes of the observed element's characterData. Example:

HTML

<span class="observable" contenteditable="true">12345</span>

JS

var observables = document.querySelector('.observable');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation);
  });    
});

var config = {characterData: true, subtree: true};
observer.observe(observables, config);

FIDDLE

Note that subtree has to be true because the text actually is a child element of the observed element.

The accepted answer might not work on all browsers if the text being updated via the innerHTML property. In this case, Firefox (as of 28) treats this as a childList event type, while Chrome (as of 33) treats this as a characterData event type. My guess is Chrome checks if the child node being update is a text node.

Firefox will fire characterData mutation events if the text is updated via user input (like via contenteditable as in the example).

In conclusion, if you want to watch for Javascript updating the innerHTML of an element, make sure to add childList:true to your MutationObserverInit object to be compatible with Firefox.

Eric

Just in case anyone is looking for a way to do this for multiple nodes. fiddle Further reading

HTML

<span class="observable" contenteditable="true">13436</span>
<span class="observable" contenteditable="true">13235</span>

JS

var observables = document.querySelectorAll('.observable');
console.log(observables);
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation);
  });
});

var config = {
  characterData: true,
  subtree: true
};
observables.forEach(function(node) {
  observer.observe(node, config);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!