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: /
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/ggwb2ejy/
Share Improve this question asked Oct 24, 2014 at 9:11 NamenoneNamenone 3442 gold badges6 silver badges19 bronze badges1 Answer
Reset to default 10You 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744073724a4554010.html
评论列表(0条)