javascript - How can I add an event listener that triggers whan a certain type of element is added to the DOM? -


i want call specific method whenever new iframe created in current window . youtube iframe player need listen new iframes whenever created or enabled in current window . possible ? please let me know if there way .i have tried below code code wont detect new iframes dynamically created . tried in google didn't info

const iframes = document.getelementsbytagname('iframe');   foreach(iframes, (iframe) => {         addeventlisteners(iframe);        }     }   }); 

you can use mutationobserver. lets listen mutations dom; setting event listener on dom itself, , listening whenever iframe added it:

(new mutationobserver(mutations => {     mutations[0].addednodes.foreach(node => {         if (node.tagname.tolowercase() === 'iframe') {             //do stuff         }     }); })).observe(document.body, {childlist: true}); 

here listening document.body, , listening changes child nodes (a node added or deleted). foreach goes through each added node (if any) , checks if iframe. if is, need in "do stuff" line.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -