Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda