Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To utilize a Mutation Observer to add an onClick event function to a button that appears after the page has finished loading, you can follow these steps:

  1. Create a new Mutation Observer object and specify the target element that you want to observe for changes.
const target = document.querySelector('#target-element');
const observer = new MutationObserver(onMutation);
observer.observe(target, { childList: true });
  1. Define a function that will be executed whenever a mutation occurs on the observed element. In this function, you can check if the button element has been added to the DOM and add the event listener to it.
function onMutation(mutationsList, observer) {
  for (let mutation of mutationsList) {
    if (mutation.type === 'childList') {
      const addedNodes = [...mutation.addedNodes];
      const button = addedNodes.find(node => node.nodeName === 'BUTTON');

      if (button) {
        button.addEventListener('click', onClick);
      }
    }
  }
}
  1. Define the onClick event listener function that will be executed when the button is clicked.
function onClick(event) {
  console.log('Button clicked!');
}

Note: Replace '#target-element' in step 1 with the selector of the parent element that contains the button element you want to observe.