Hey, I'm currently working on a mini project for practice and ran into an issue. The loop is functioning properly for the hard coded code but not for the dynamically generated one.
<button class='agree'>Add Like</button>
Then, I have a function that essentially adds the number of likes below it.
for(var i = 0; i < agreeBtn.length; i++) {
agreeBtn[i].addEventListener('click', plusAgree)
}
function plusAgree (e) {
let newNum = Number(this.children[1].innerText) + 1;
this.children[1].innerText = newNum;
}
This code works well for the hard coded button elements. However, when I apply it to a newly created element using createElement and innerHTML (dynamically typed), the event listeners stop working.
let newDiv = document.createElement('div');
newDiv.className = 'boxshadow post-div grid-x';
newDiv.innerHTML = `
<div class="cell small-10">
<h3 id='post-title'>${postContent.title}</h3>
<p id='post-description'>${postContent.description}</p>
</div>
<div class="cell small-2 icon-div" id="icon-div">
<button class='agree' id=${agreeId()}>
<i class="fas fa-thumbs-up fa-3x"></i>
<h5 c
lass='agree-num'></h5>
</button>
How can I change 'this' in the dynamically typed element to refer to the button instead of the global object? Thank you