В моем приложении я применяю фильтры к определенным узлам и не хочу фильтровать дважды по наличие как родительского, так и дочернего узла с фильтром. Я использую описанный выше подход для обработки динамического DOM. Это также расширение для браузера, и оно должно обрабатывать произвольный контент как можно дешевле и ненавязчивее.
Код: Выделить всё
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
$(mutation.addedNodes).find('*').addBack().each(function(i, node) {
//all added nodes come through here
if ($(node).data('count')) {
//a child has already been processed so must be a branch
$(node).addClass('branch');
} else {
//set ancestors as .branch and increment their count
$(node).parents('div').each(function() {
$(this).removeClass('leaf').addClass('branch');
$(this).data('count', ($(this).data('count') || 0) + 1);
});
//no children have been processed so must be a leaf
$(this).addClass('leaf');
}
});
$(mutation.removedNodes).find('*').addBack().each(function(i, node) {
//FIXME: parentNode is null
console.log(node, node.parentNode);
//decrement ancestor counts and set as leaf if zero
$(node).parents().each(function() {
$(this).data('count', $(this).data('count') - 1);
if ($(this).data('count') == 0)
$(this).removeData('count').removeClass('branch').addClass('leaf');
});
});
});
});
observer.observe(document, {
subtree: true,
childList: true
});
//for debugging counts
$(document).on("mouseenter", "div", function() {
$(this).attr('title', $(this).data('count'));
});
$(document.body).append('');
//add some divs
window.setTimeout(function() {
$('div').eq(0).append('');
$('div').eq(0).append('');
}, 500);
//remove divs
window.setTimeout(function() {
$('div').eq(2).remove();
}, 1000);Код: Выделить всё
div {
min-height: 60px;
border: 1px solid black;
margin: 10px;
background-color: white;
}
.branch {
background-color: #a3aff5;
}
.leaf {
background-color: #f5a3a3;
}Код: Выделить всё
Подробнее здесь: https://stackoverflow.com/questions/350 ... ore-it-was
Мобильная версия