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

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

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 Denunciar

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