1

I have this template:

<template id="a">
   <div class="b">
        <h1 class="placeholder1"></h1>
        <div class="info hide">
            <p class="p1"></p>
        </div>
    </div>

I am cloning it with:

fetch("json/countries.json").then(res => res.json()).then(list => show(list));
function show(list) {
    list.forEach(function (list) {
        const clone = template.cloneNode(true);
        clone.querySelector(".placeholder1").textContent = list.country;
})}

I am trying to add an event listener to each cloned object, but the result is that it only adds it to the first cloned element, not the rest.

clone.querySelector(".placeholder1").addEventListener('click', fx_button1);
function fx_button1(){
    document.querySelector(".info").classList.toggle("hide");
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
tintinve
  • 87
  • 12
  • Possible duplicate of [querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript](https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid) – Ele Apr 02 '18 at 22:02

1 Answers1

0

querySelector MDN only selects the first match found from the given selector. You need to use querySelectorAll MDN and then iterate the results.

var cloneSet = clone.querySelectorAll(".placeholder1");
for(var i = 0; i < cloneSet.length; i++){
    cloneSet[i].addEventListener('click', fx_button1);
}
Travis J
  • 81,153
  • 41
  • 202
  • 273