Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
Change url path of a dynamically generated <a> element

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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')
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!