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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-25 23:13:33 +0000
Seen: 8 times
Last updated: May 25 '23
In Angular, how can a mat cross button be aligned to the right-most position within a div?
How can I detect the fullscreen button click event of an HTML5 video?
What is the method for modifying the button color in the antd Modal?
How can I create an HTML button that sends data to a different URL?
How can we use the Pywinauto library to automate the control of Proton VPN?
How can a button be utilized to display and hide the matplotlib live graph?
How can I activate a button using Angular Material?
Is it impossible to modify the color of button text on Android?
How can key and value be saved in admin setting using Opencart 3?