I have this <a class="myclass" href="#">test</a> element which appears dynamically on a page, how do I modify the href as soon as I find the element with myclass?
My initial approach has been to add a onclick eventlistener as shown below but doesn't seem to "overwrite" the original href url
$('body').on('click', '.myclass', function(){
window.location.href = "https://abcdef.com";
});
I could add a check every 1000ms and use getElementsByClassName but doesn't look like a good approach
Use a MutationObserver to listen for changes in the body's childList and change the href attribute of the element should it be an anchor:
let observer = new MutationObserver(records => {
for (const record of records) {
for (const added of record.addedNodes) {
if (added.nodeType == 1) {
added.href = "https://stacksnippets.net"
}
}
}
});
observer.observe(document.body, {
childList: true
});
setTimeout(() => document.body.innerHTML += `<a class="myclass" href="#">dynamically added anchor</a>`, 1000)
I have been using it in my projects for a while
function waitForElm(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
To use it:
waitForElm('.some-class').then(elm => console.log(elm.textContent));
or with async/await
const elm = await waitForElm('.some-classs')