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?
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?
Share Improve this question edited May 23, 2017 at 10:33 CommunityBot 11 silver badge asked Aug 24, 2016 at 12:24 Maxim ToybermanMaxim Toyberman 2,0061 gold badge23 silver badges36 bronze badges 8- 1 Possible duplicate of How to react to a specific style attribute change with mutation observers? – woxxom Commented Aug 24, 2016 at 12:44
- 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 Commented Aug 24, 2016 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 Commented Aug 24, 2016 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 Commented Aug 24, 2016 at 13:05 - 1 @wOxxOm thank you, especially for bringing up not using jquery! – EasyBB Commented Aug 24, 2016 at 13:15
1 Answer
Reset to default 8Use 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).