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:
const target = document.querySelector('#target-element');
const observer = new MutationObserver(onMutation);
observer.observe(target, { childList: true });
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);
}
}
}
}
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.