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>
没有评论:
发表评论