I'm trying to use MutationObserver to check for new rows being added inside of a table, the code I've got below seems to work for H2 elements, however when I change this to Table rows, the console.log doesn't output to the console, if i inspect the table, the TR's are being added. Does anyone have any ideas? I can't figure out why it wont observe table row's being added
var list = document.getElementById("testtable");
var MutationObserver = window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
console.log("mutation!");
}
});
});
observer.observe(list, {
attributes: true,
childList: true,
characterData: true
});
var element = ("tr");
setInterval(
function(){
$(list).append("<h2>" + "THIS IS A TEST" + "</h2>");
//This doesn't work
//$(list).append("<tr>" + "<td>" + "<h2>" + "THIS IS A TEST" + "</h2>" + "</td>" + "</tr>");
},
2000);
Here's a working fiddle: http://jsfiddle.net/ggwb2ejy/
“MutationObserver” is a Web API provided by modern browsers for detecting changes in the DOM. By using this API you can listen to changes in DOM, like added or removed nodes, attribute changes or changes in the text content of text nodes and make changes. Web apps are getting complex on the client-side nowadays.
MutationObserver is a Web API provided by modern browsers for detecting changes in the DOM. With this API one can listen to newly added or removed nodes, attribute changes or changes in the text content of text nodes.
Introduction to the JavaScript MutationObserver API When the DOM nodes change, you can invoke a callback function to react to the changes. Third, call the observe() method to start observing the DOM changes. The observe() method has two parameters. The target is the root of the subtree of nodes to monitor for changes.
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.
You need to set the subtree
option to true
observer.observe(list, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
When you add a tr
it is not directly added to the table
it is added to a tbody
element, so in reality a subtree of the observed element is modified. To observe any changes in the subtree you need to set subtree: true
in the configuration
Demo: Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With