2021年4月29日星期四

How Dynamically Created Button Target Individual Element

I am under the impression if we target an element by element name of class name it will be applicable to all elements or elements with that class name. But in the following code when I clicked a button it will only change the innerHTML of the nearest span element even though I have add event listener by selecting just button element. Please clarify. Thanks.

const myArray = [0, 1, 2];    let myContainer = document.querySelector('.container');    const newArray = myArray.map((item) => {      let newArticle = document.createElement('article');      const myHTML = `<article>                      <span></span>                      <button>Click ${item}</button>                      </article>      `;      newArticle.innerHTML = myHTML;        let myBtn = newArticle.querySelector('button');        myBtn.addEventListener('click', (e) => {          newArticle.querySelector('span').innerHTML = 'clicked';      })        return newArticle;  });    newArray.forEach((item) => {      myContainer.appendChild(item);  });
<div class="container">  <section>  </section>  </div>
https://stackoverflow.com/questions/67327686/how-dynamically-created-button-target-individual-element April 30, 2021 at 11:06AM

没有评论:

发表评论