Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda