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

183
Visualizações
can't select element created using map() function

I have displayed some element using Array.map function but now i cannot select any element that are created using Array.map function.when I select console log an element that is created using that map function it shows null

const fetchData = function() {
  let display = products.map(function(product) {
    return `<div class="main relative lg:w-1/4 md:w-1/2 p-4 w-full">
<a class="block relative h-48 rounded overflow-hidden">
  <img
    alt="headphone"
    class="product--img object-cover object-center w-full h-full block"
    src=${product.img}
  />
</a>
<div class="mt-4 relative">
  <h3 class="category text-gray-500 text-xs tracking-widest title-font mb-1">
   ${product.category}
  </h3>
  <h2 class="name text-gray-900 title-font text-lg font-medium">
   ${product.name}
  </h2>
  <p class="price mt-1">${product.price}</p>
  <button
id="name"
    class="btn-add  absolute right-5 bottom-3 bg-orange-400 rounded text-sm px-2 py-2 text-white font-medium"
  >
    Add To Cart
  </button>
</div>
</div>`;
  });

  display = display.join("");
  mainSection.innerHTML = display;
};


window.addEventListener("DOMContentLoaded", fetchData);

let btnAdd = document.querySelector(".btn-add")

console.log(btnAdd)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Put

let btnAdd = document.querySelector(".btn-add")

console.log(btnAdd)

inside fetchData at the very bottom, when the .btn-add is already created and appended to the DOM.

You try to access .btn-add when it hasn't exist yet, DOMContentLoaded event hasn't fired yet. window.addEventListener("DOMContentLoaded", fetchData); here you only add a listener, but not execute, so your HTML in display variable hasn't exist yet

about 4 years ago · Juan Pablo Isaza Relatório

0

It happens that the fetchData method is called only after the DOM finishes loading, but the search for the element of your button is performed even before the loading of the DOM is finished (and in any case the element does not yet exist and the value is null) If you search for the value "after" the loading of the DOM it will find the element

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