Attaching EventListeners to fresh DOM elements

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

![ Here is the result for hardcoded ]1

![This is what i got from the newly created element ]2

Answer №1

this points to the global object because the function is called in the global scope.

It's recommended to utilize the .bind() method in this scenario.

The bind() method generates a new function which, when executed, has its this keyword set to the specified value.

Here is a demonstration:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Controller is not able to retrieve the Route Parameter, resulting in a 404

Currently working on my very first web app using Node.js and AngularJs. I've encountered a roadblock with the following code: var app = angular.module('Martin', ['ngResource','ngRoute']); app.config(['$routeProvide ...

Tips for updating the input field value when clicking on dynamically generated edit icons

Within this code, there is an ajax function that assigns values to fields, along with dynamically created edit icons. Each address added in the database generates a new edit icon. My requirement is to have each button alert its id value when clicked. Below ...

Using JQuery to encapsulate the contents of a variable

I am working with a variable that stores HTML retrieved from an HTML5 SQL database. When I use the .append() method to add it to a DOM element, everything works as expected. However, I want to wrap the HTML contents before appending them, so I tried using ...

Encountered difficulties while attempting to use keyboard input and received a null value when attempting to retrieve a data-* attribute using Python and Selenium

Encountered an issue with keyboard interaction and finding a null value for the data-* attribute during automated login attempts on Gmail using Python and Selenium While attempting to automatically log in to Gmail using Python and Selenium, I successfully ...

The jspdf function is not displaying any images in the PDF file

I am new to coding and encountered an issue when trying to download images in reactjs. After clicking the download button, I only receive a blank pdf file. https://i.stack.imgur.com/0XJcC.png The function in my react code that attempts to generate the p ...

Enhancing the angular options list with new commands

Is there an easy way to append specific commands to the end of an Angular select box? For instance, I want a list that looks like this: Cat Dog Octopus Browse… All items except Browse are data values bound using ng-options, while Browse is a command t ...

Modify the data within the SVG code

I am working with an SVG string and I found a helpful answer on how to get information from a svg string in javascript? using jQuery. However, I am now wondering how to change attributes within the SVG. For example, how can I change the height of the rect ...

Ensuring that $.each properly processes all deferreds in jQuery

I am currently working with the following jQuery code: myFunc: function(cmd, obj){ var idToExtMap = this.map; var requireRes = this.reqInst; var deferreds = []; var ret = true; $.each(idToExtMap[cmd], function( ...

Images cascading like a downpour on a canvas (Javascript)

I have been experimenting with canvas, attempting to create a simulation of random falling objects. I've successfully drawn the background image, but I'm having trouble with the second image that is supposed to simulate a rain drop. I've ma ...

"Retrieving an element from an array may result in a value of

While going through an array of objects in my Angular component class, I faced a strange issue where the properties kept showing up as undefined. The function responsible for this behavior looks like this: upload(): void { const { fileHandles, related ...

The detection of my query parameters is not working as expected

Creating an Angular application that dynamically loads a different login page based on the "groupId" set in the URL is my current challenge. The approach involves sending each client a unique URL containing a specific "groupId" parameter. A template is the ...

Guide on setting up Facebook Ads for IOS with React Native

I'm encountering an issue in React Native while attempting to launch my app on IOS, where a warning message is displayed: "Module AdChoiceManager requires main queue setup since it overrides 'init' but doesn't implement 'requiresM ...

Feeling overwhelmed by JavaScript jQuery errors when making an Ajax request?

I am facing an issue with two buttons on my webpage. One button triggers a table refresh using an ajax php request, while the other button is set to automatically refresh the table every 10 seconds. However, when attempting to access the document, I am enc ...

JavaScript - Attempting to insert a value into a text field by clicking a button

I am struggling to get my function to properly add the value of the button to the text field when clicked by the user. HTML <form name="testing" action="test.php" method="get">Chords: <textarea name="field"& ...

Foundational JS object and MIME in reference to a simple web server script

Recently, I started learning programming using JavaScript and decided to focus on Angular and Node.js for server-side development. After going through the Angular tutorial, I have a few questions about the web-server.js file provided. Since the server aspe ...

Access a particular html tag as a value within an object

Recently, I've been working on AngularJS version 1.6 and am faced with an API containing multiple objects structured similar to the example below: { "description": " <p><a href=\"url">link</a>text</p><p><a href ...

We're sorry, but there seems to be an issue with locating the module: 'react-scroll-horizontal'

Encountering the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/react npm ERR! reac ...

Transforming an HTML Attribute into a JavaScript Object

I'm encountering an issue with converting an HTML-data attribute into a JavaScript Object. Here is my approach: The data Attribute appears as: <a id="stringObj" data-string="{'Foo':'Bar'}">Some A-Tag</a> In JavaScri ...

Class-based Button Transition Effect failing to operate as intended

I want to trigger these 3 events simultaneously when a form is filled out, all initiated by the same button. I have been able to make it work using 3 classes named: "draw dj", which represents the first event "draw1 dj", which signifies the 2nd event "d ...

Issue during Firebase production: emptyChildrenSingleton isn't recognized

In my nextjs project, I am using React v18.1.0 and Firebase Realtime Database for handling notifications. The notifications work fine in development mode but fail in the production environment. The errors I encountered are as follows: ReferenceError: empt ...