Home > Blockchain >  can't select element created using map() function
can't select element created using map() function

Time:02-11

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 >
<a >
  <img
    alt="headphone"
    
    src=${product.img}
  />
</a>
<div >
  <h3 >
   ${product.category}
  </h3>
  <h2 >
   ${product.name}
  </h2>
  <p >${product.price}</p>
  <button
id="name"
    
  >
    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)

CodePudding user response:

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

CodePudding user response:

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

  • Related