Reputation: 55
Hi im currently making a mini project just for practice but i came across this problem. The loop work for the hard coded code, but not the dynamiclly type one
<button class='agree'>Add Like</button>
then i have a function to basiclly adding number of likes bellow 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 fine for the hard coded button elements. But when i apply it to a new element which i have just created with createElement and innerHTML (dynamicly typed), the event listeners just doesn't work anymore.
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 class='agree-num'></h5>
</button>
how can i change the this for the dynamiclly typed one to refer to the button, instead of the global object? thanks
![ Here is the result for hardcoded ]1
![This is what i got from the newly created element ]2
Upvotes: 0
Views: 29
Reputation: 2799
this
refers to the global object because the function gets invoked in the global scope.
It's best to use the .bind()
method here.
The
bind()
method creates a new function that, when called, has itsthis
keyword set to the provided value.
Here is an example:
const agreeBtn = document.getElementsByClassName("agree");
for (var i = 0; i < agreeBtn.length; i++) {
const el = agreeBtn[i];
el.addEventListener('click', plusAgree.bind(el));
}
function plusAgree(e) {
console.log(this);
}
<button id="agree1" class="agree">Agree Button</button>
<button id="agree2" class="agree">Agree Button</button>
Upvotes: 1