Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!