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

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

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