1

How can I add a global listener in Javascript such that I see which html element (like a div, span, etc..) is created, and can decorate them if required?

In my case I want to add an class attribute to an html "input" element, if certain conditions are met.

It's an interactive website, so elements are created dynamically, so I can't do it when the page loaded as the input elements aren't created yet.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
edbras
  • 4,145
  • 9
  • 41
  • 78
  • 3
    Possible duplicate of [Detect changes in the DOM](http://stackoverflow.com/questions/3219758/detect-changes-in-the-dom) See also [Most Efficient Method of Detecting/Monitoring Dom Changes](http://stackoverflow.com/questions/2457043/most-efficient-method-of-detecting-monitoring-dom-changes) – CollinD Feb 13 '17 at 17:51
  • 1
    You mean this api? https://developer.mozilla.org/en/docs/Web/API/MutationObserver – Josué Zatarain Feb 13 '17 at 17:51
  • I looked at it, and played with it, but I don't think it's a duplicate. I want to be informed on "every" creation of an InputElement somewhere on the DOM, while with MutationObserver I have to specify the Element that I want observe DOM mutations and it will inform me only the mutations on the Element I specify. But I have no idea which Element to specify. If I specify the BODY, I see only a few elements that are added/removed, I am not informed about an INPUT element that is created as a Child of a Child of the BODY. Or am I missing something? – edbras Feb 14 '17 at 18:49
  • I found it: yes it's duplicate. I used the MutationObserver with the subtree option. I used the childList option but that wasn't enough. I now get informed when any input element is created anywhere on the screen. – edbras Feb 15 '17 at 10:50

1 Answers1

2

MutationObserver provides developers a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification. ..for more details

Example :

// select the target node
var target = document.getElementById('some-id');

// create an observer instance
var observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • Should 'some-id' be the id on the ? And how to add attributes to the element that is created and received by the listener ? – edbras Feb 13 '17 at 18:09