2

I need to get data when a specific attribute is added . I have read this post : Is there a JavaScript/jQuery DOM change listener?

  var observer = new MutationObserver(function (mutations, observer) {
    // fired when a mutation occurs
     $.each(mutations, function(index, mutation) {

      var post = $(mutation.target).find('div[class^="ContentWrapper"]');


     });
  });
  observer.observe(document, {
    subtree: true,
    attributes: true

  });

There is a problem with this approach because there are to many events and the extension is very slow,is there an option to filter the mutations,by specific attribute?

Community
  • 1
  • 1
Maxim Toyberman
  • 1,906
  • 1
  • 20
  • 35
  • 1
    Possible duplicate of [How to react to a specific style attribute change with mutation observers?](http://stackoverflow.com/questions/39024163/how-to-react-to-a-specific-style-attribute-change-with-mutation-observers) – wOxxOm Aug 24 '16 at 12:44
  • this is not good....it will give me all the added class's,i want a specific class @wOxxOm – Maxim Toyberman Aug 24 '16 at 12:54
  • 2
    This is the only method to limit attribute observation. Be creative. Don't observe the entire document, do it on the parent container, for example. – wOxxOm Aug 24 '16 at 12:57
  • 4
    Also NEVER use jQuery and other monster wrappers in a mutation observer, switch to direct DOM access: `for (var i=0; ....) { var post=mutations[i].target.getElementsByClassName('ContentWrapper')[0]; ...... }` – wOxxOm Aug 24 '16 at 12:59
  • 1
    Alternatively, if you can observe the immediate parent element for added nodes (and then attach another observer to watch for attribute on each of those added nodes) then you won't need `subtree: true,` so your observer will be super fast even with jQuery. – wOxxOm Aug 24 '16 at 13:05
  • 1
    @wOxxOm thank you, especially for bringing up not using jquery! – EasyBB Aug 24 '16 at 13:15
  • @wOxxOm Thank you !! for the explanation – Maxim Toyberman Aug 24 '16 at 13:33
  • [MutationSummary](https://github.com/rafaelw/mutation-summary) Could help you. Give it a target and it will give you a summary of everything that's happened (within reason). I.e. A summary of DOM Events/Mutation Events. Hope it helps. There's an example on the github of it's use. – hipkiss Sep 02 '16 at 18:37

1 Answers1

5

Use attributeFilter in the MutationObserverInit options. Set it to an array of attributes that you want to listen for like so:

var attributeSpecificObserver=new MutationObserver(function_you_want_observing);
attributeSpecificObserver.observe( element_you_want_to_observe, {
    attributeFilter: ['id', 'class', 'style', 'etc'],
} );

Source: Mozilla Developer Network (MDN).

Bernat
  • 825
  • 1
  • 6
  • 10
Jack G
  • 4,553
  • 2
  • 41
  • 50