Mutation Observer only get specific content

南笙酒味 提交于 2019-12-23 04:43:51

问题


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, use eq ,ethod
  • Remove for, add forEach

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!