问题
I have the following structure:
<div class="wrapper">
<div class="col">left</div>
<div class="col">middle</div>
<div class="col">right</div>
</div>
Now I want to get the nodes ONLY if INSIDE $('.col') a div of class "block" is included like:
YES for THIS:
$('.col')[1].append($('<div class="block">urgent</div>'));
but NO for THIS:
$('.col')[1].append($('<div class="different">dontcare</div>'));
my Observer looks like this:
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
console.log(mutation.addedNodes[i]);
}
});
});
observer.observe(document, {
childList: true,
subtree:true,
characterData:true,
attributes:true
});
I am inside a chrome extension, but that should not really matter
回答1:
Modified your code:
$('.col')[1].append
throw a TypeError, because you use jQuery function on DOM Node, useeq
,ethod- Remove
for
, addforEach
I added the check for .block
element in mutation.addedNodes
NodeList via
addedNode.classList.contains('block')
My code:
$(function () {
'use strict';
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
[].slice.call(mutation.addedNodes).forEach(function (addedNode) {
if (addedNode.classList.contains('block')) {
console.log("I'm has a class block, whats next?");
}
});
});
});
observer.observe(document, {
childList: true,
subtree:true,
characterData:true,
attributes:true
});
//Yes
$('.col').eq(1).append($('<div class="block">urgent</div>'));
//No
$('.col').eq(1).append($('<div class="different">dontcare</div>'));
});
来源:https://stackoverflow.com/questions/27828917/mutation-observer-only-get-specific-content