Whenever a DOM element changes, we can capture it using MutationObserver. Basically you can create a new MutationObserver(callback)
instance and then invoke the observe(targetNode, config)
function.
On a recent project there was a shop plugin I was using in a cart page. Every time user updated quantity, the form element’s id was changing randomly and I did not know how to access its reference.
In a situation like this, you can add a parent element to that <form>
and observe that parent element for mutation changes.
<div id='parent'>
<form id='some-random-id'>
</form>
</div>
When the page loads, just track the parent
div;
// We gotta update this whenever the expected mutation happens
let globalFormReference = null
const parentNode = document.querySelector('#parent')
// Most of the time you want to set these to true, otherwise callback won't be invoked
const config = { attributes: true, childList: true, subtree: true }
// Initialize the observer with an anon callback as parameter
const observer = new MutationObserver((mutationsList, observer) => {
for(const mutation of mutationsList) {
// This was my condition, you can update here to your needs
if(mutation.type === 'childList' && mutation.attributeName === 'id' && mutation.target.nodeName === 'FORM') {
globalFormReference = mutation.target
// Always good to disconnect the observer if you are done here
observer.disconnect()
}
}
})
observer.observe(parentNode, config)