Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to intercept innerHTML changes in javascript?

Tags:

I need to intercept any changes in the content of a cell inside my webpage.

The following code shows me that addEventListener does not work.

function modifyText() {
alert("!");
}

var el=document.getElementById("mycell");
el.innerHTML="a"
el.addEventListener("change", modifyText, false); 
// After next instruction I expect an alert message but it does not appear...
el.innerHTML="Z";

The code is just a toy example. In my real case the changes in the page (and therefore in the cell, too) are made by a webapp that I have NO control over.

like image 889
tic Avatar asked Sep 11 '11 21:09

tic


2 Answers

There is a modern way to catch innerhtml changes:

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe

Example:

// identify an element to observe
elementToObserve = window.document.getElementById('y-range').children[0];

// create a new instance of 'MutationObserver' named 'observer', 
// passing it a callback function
observer = new MutationObserver(function(mutationsList, observer) {
    console.log(mutationsList);
});

// call 'observe' on that MutationObserver instance, 
// passing it the element to observe, and the options object
observer.observe(elementToObserve, {characterData: false, childList: true, attributes: false});

childList mutation fires on innerHTML change.

like image 179
legale Avatar answered Sep 16 '22 21:09

legale


You can't listen to a DOM element change that way. change event is mostly for inputs

There is some other new DOM 3 events that would help you on this.

Here is some:

DOMCharacterDataModified //Draft

DOMSubtreeModified

like image 45
Mohsen Avatar answered Sep 18 '22 21:09

Mohsen