Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected.

How can I fix the issue with the click event not working? The gets function is called once the AJAX request is complete. If I remove the event listener and replace it with directly showing an alert box, it works fine. But adding the event listener fails to bind a handler to the target div.

function gets(){
    document.getElementById("test").children[6].addEventListener("click", function() {
        alert(document.getElementById("test").children[6])
    })
}

Answer №1

A solution for this issue is to utilize event delegation.

Here is a demonstration of how it operates:

function fetch() {
  document.getElementById("example").addEventListener("click", function(event) {
    console.log(event.currentTarget.children[0])

  })

The currentTarget represents the element being clicked on, while the target refers to its parent.

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

Why do I see my footer displayed twice on the page?

<div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li> @Ajax.ActionLink("Imagenes List", "Images", "Home", new { page = 0 }, new AjaxOptions() ...

Animating a JQuery Slider using code from scratch

I'm attempting to dynamically alter/animate a JQuery slider. In this scenario, there are two arrays present: one for the values that need to be modified and another for the durations between modifications. By monitoring the console, you'll observ ...

Implementing Firebase pagination alongside Mui-Datatable pagination and sorting capabilities

I've been trying to implement server-side pagination and filtering for the Mui-Datatable to display my data, but I haven't been successful so far. Here are the snippets of code that I have been working on: One issue that I'm facing is that ...

Express router parameter matching

Let's consider a scenario where I have two routes - one with parameters and one without: /foo?bar /foo I aim to assign different handlers for these routes. Instead of the conventional approach, I am looking for a way to simplify the code. app.use(&a ...

Angular transitionTo failing to refresh state post AJAX call

Issue: I am struggling to display updated data in a different state following the receipt of an AJAX request. Current status: In one state, I have a form for editing data. In another state, I display the edited data. After submitting the form, an AJAX ...

Smart method for repositioning multiple elements on the display

Imagine we have multiple divs displayed on a screen: https://i.stack.imgur.com/jCtOj.png ...and our goal is to move them collectively, either to the left: https://i.stack.imgur.com/KBfXC.png ...or to the right: https://i.stack.imgur.com/c1cUw.png An ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Updating a table dynamically after a form submission using jQuery, Ajax, and PHP without needing to refresh the page

My current setup involves an ajax form along with a table. Here is the ajax code I am using: $(function () { $(".submitann").click(function () { var title = $("#title").val(); var announcement = $("#announcement").val(); var d ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

Encountered an error in NodeJs with mongoDB: TypeError stating that property 'fullname' is not defined

I am having issues storing user-entered data from an HTML form into MongoDB. The error message I receive is "TypeError: cannot read property 'fullname' of undefined" TypeError: Cannot read property 'fullname' of undefined at C:&bso ...

Leveraging the outcome of JSON within PHP variables

I would like to completely rewrite my question. My goal is to update the display of five variables without having to reload the entire page. I have a PHP file called check_conf_update.php which executes a query, retrieves data, and converts it into JSON ...

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

Include a new class in the classList of an element at a specific index

Is it possible to add a class to a specific position in order to maintain a certain order, especially when it goes against the logic that targets the class based on its position? link.closest('item').classList.add('c-class') // Contrad ...

What could be causing the state to continuously appear as null in my redux application?

Currently, I am in the process of developing a basic contacts application to gain expertise in React and Redux. The main focus right now is on implementing the feature to add a new contact. However, I have encountered an issue where the state being passed ...

The height of a DIV element can vary based on

Looking at this div structure: DIV3 has a fixed height. The nested DIV5 will be receiving content from Ajax, causing its height to change. Additionally, there are some DHTML elements inside it that also affect the height. DIV5 has a fixed min-height set. ...

Experiencing AJAX errors 403 and 404 despite successful implementation in other instances

I am facing a perplexing issue with my code that is causing a 403 error when attempting to delete a row. The strange thing is, the code works perfectly on another website I created. The concept is quite simple - attaching an event listener to a button trig ...

"Encountered a type error: The .join method is not recognized as a function

Hello everyone, I've encountered an issue that has me a bit stumped. I recently took over a project and found a problem in which the previous developer was attempting to join an array of strings. Unfortunately, when I try to build the project, I keep ...

Discovering numbers within a JSON object and extracting them - a step-by-step guide

If I have a JSON object coming from a random dataset and want to search through it to manipulate the number values, how can I achieve this? Looping through the object using for...of allows me to get the keys, but I'm unsure how to access every key-val ...

Hosting a WCF service in a virtual directory on a shared hosting environment

In the midst of my work on a next js project, I encountered the need to invoke a wcf service. To rectify an error caused by the secure server hosting the site, necessitating the service also be hosted securely, I resorted to creating a virtual directory ...

Determine the central x and y coordinates of elements depending on the specified screen dimensions

Is it possible to determine the center position of an element at a specific screen size using jQuery? I am looking to calculate the center position of an element based on provided height and width dimensions. For instance, if I provide the screen size (1 ...