Home > Back-end >  Change url path of a dynamically generated <a> element
Change url path of a dynamically generated <a> element

Time:10-30

I have this <a href="#">test</a> element which appears dynamically on a page, how to 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

CodePudding user response:

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')

CodePudding user response:

You could do something like this, use an eventListener and then set the href property of an element (overwritting it if it already exists).

const classEl = document.querySelector('.myclass');
const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
    if (classEl) {
        classEl.href = 'https://stackoverflow.com/';
        classEl.innerText = 'stack overflow';
    } else console.log('no element found in DOM');

})
<a class="myclass" href="#">test</a>
<button id="btn">test</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related