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

208
Vistas
JavaScript works when setTimeout() is used, but it isn't working when document.eventListener('DOMContentLoaded', x) is used on a WordPress page. Why?

I have a few lines of JavaScript code that pick up heading texts from separate sections and place them into their respective input fields. They are also executed on single pages using wp_enqueue_script.

It works absolutely fine when setTimeout() is used:

function passengerElevator() {
  var getProductName = document.querySelectorAll('[data-id="6657316"]');
    getProductName.forEach(function(item) {
      var productName = item.querySelector('.lift');
      var inputArea = item.querySelector('input[name=product]');
      inputArea.value = productName.innerText;
  });
  var getProductName = document.querySelectorAll('[data-id="e9c06d5"]');
    getProductName.forEach(function(item) {
      var productName = item.querySelector('.lift');
      var inputArea = item.querySelector('input[name=product]');
      inputArea.value = productName.innerText;
  });
setTimeout(function() { passengerElevator() },3000);

However, there is problem of page size (some pages have more than 10 input fields) and I don't want to set an astronomically high ms to delay the script. So I decided to fire it on DOMContentLoaded:

document.addEventListener("DOMContentLoaded", passengerElevator);
function passengerElevator() {
  var getProductName = document.querySelectorAll('[data-id="6657316"]');
    getProductName.forEach(function(item) {
      var productName = item.querySelector('.lift'); // heading text (ex:Panoramic Lift)
      var inputArea = item.querySelector('input[name=product]');
      inputArea.value = productName.innerText; //ouput here
  });
  var getProductName = document.querySelectorAll('[data-id="e9c06d5"]');
    getProductName.forEach(function(item) {
      var productName = item.querySelector('.lift'); // Heading text (ex:Home Lift)
      var inputArea = item.querySelector('input[name=product]');
      inputArea.value = productName.innerText; // Output here
  });
}

As you may have already guessed, it is not working. Is my code too messy to be executed faster or is there any other problem I am missing?

I know similar questions have been asked previously, however, no existing answer I found was able to help me.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It seems like you try to loop through elements that are still not loaded. Perhaps they are being appended to the page via Ajax, so DOMContentLoaded can't help there.

You can create your own check for those elements using setInterval, so use something like this:

let dataIdCheck = setInterval(() => {
    if (document.querySelectorAll('[data-id="6657316"]').length > 0 && document.querySelectorAll('[data-id="e9c06d5"]').length > 0) {
        clearInterval(dataIdCheck);

        // your code here
    }
}, 500);

This code will run every 500 milliseconds and check if those two elements exists, using .length. Once they do exists, we stop the interval and run the code.

I also suggest to do console.log('in') to check that our interval stop running once the elements are found.

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