addEventListener on dynamically created elements not working

event binding on dynamically created elements javascript
angular add event listener to dynamically created element
how to bind click event in jquery for dynamically added html element
jquery on click function not working after appending html
javascript add onclick event dynamically
event binding on dynamically created elements react
javascript add class to dynamically created element
access dynamically created element jquery

I want to add click events to images present in inner html. But when I try to add it, it won't work.

Template

<div [innerHTML]="myHtml"></div>

Code

myHtml;

ngOnInit() {
    const root = document.createElement('div');
    root.innerHTML = this.getHtml();
    const images = root.getElementsByTagName('img');
    Array.prototype.forEach.call(images, (image: HTMLImageElement, i) => {
      image.addEventListener('click', (event: any) => {
        console.log('click', event);
      });
    });
    this.myHtml = root.innerHTML;
  }

Here is the stackblitz

You need to use ngAfterViewInit() to achieve this, I have modified the code and is working fine.

Please check the link https://stackblitz.com/edit/angular-7da7cd

Hope this helps.

Attach event to dynamic elements in javascript, This is due to the fact that your element is dynamically created. addEventListener('click',function(e){ if(e.target && e.target.id== Sometimes pure JS solution does not work on iphone, but if change The _case function allows you to not only get the target, but also get the parent element where you bind the event on. To keep the event handling code of the dynamic element separate as if it is present in the DOM, the event delegation model can be used. Event Delegation — Attaching Event Handler on Parent of the Dynamically Created Element. The yet-to-be created dynamic element is not present in the DOM, so event handlers cannot be attached to it.

This may be due to restriction that event listener will be registered only for elements before page cycle starts. Did you try doing it more angular-ish way by Renderer2

this.renderer.listen('img', 'click', (evt) => {
  console.log('Clicking the document', evt);
});

Docs : https://angular.io/api/core/Renderer2

Attaching event handlers to dynamically created JavaScript elements, How do you add an event to a dynamic button? The problem with dynamically created elements, is that they aren’t born with the same event handlers as the existing elements. Let’s say we have a list of items that you could click on to toggle/add a class name, when a new element is created and appended to that same list - it won’t work - the event handler attachment is missing.

Its not yet in the DOM. Do the same with ngAfterViewInit:

ngAfterViewInit() {
    const root = document.createElement('div');
    root.innerHTML = this.getHtml();
    const images = root.getElementsByTagName('img');
    Array.prototype.forEach.call(images, (image: HTMLImageElement, i) => {
      image.addEventListener('click', (event: any) => {
        console.log('click', event);
      });
    });
    this.myHtml = root.innerHTML;
  }

document.getElementsByTagName, () method returns a collection of all elements in the document with the specified tag name, as an HTMLCollection object. The HTMLCollection object represents a collection of nodes. The nodes can be accessed by index numbers. The advantage of this approach is that you can dynamically add your element anywhere, and the click handler will 'just work', and you need not concern yourself with delegating control to parent elements, and so on.

You can use elementRef for specifying <img> element. Then you can use the following to add event listener into all <img>:

ngAfterViewInit() {
    var elem = this.elementRef.nativeElement.querySelectorAll('img');
    if (elem) {
      elem.forEach(res => {
        res.addEventListener('click', this.onclick.bind(this));
      })
    }
}

Note that:

onclick() {
    alert("Image clicked");
}

is a custom function which you can customize. And don't forget to import { ElementRef } from '@angular/core';

Stackblitz Fork.

More detail into AfterViewInit, .bind, the difference between ElementRef and Renderer

JavaScript Event Delegation is Easier than You Think, In jQuery adding event handlers to dynamic elements is quite simple. click on #​submit-button is not going to work document. addEventListener('click', function(​e) { if(e.target.id == 'submit-button') { alert('CLICKED'); } })  The EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).

Adding Event Handlers on Dynamically Created Elements with , If you try to do something with the elements that are dynamically added to DOM using the jQuery click() method it will not work, because it bind the click event  Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions, and Opera 6.0 and earlier versions. However, for these specific browser versions, you can use the attachEvent() method to attach event handlers (see "More Examples" below for a cross-browser solution).

How to Bind Click Event to Dynamically Created Elements in jQuery, I have a simple HTML document that includes a button named "click me" and also an empty div. Both element have an id. In the JavaScript file, in  i am creating a table dynamically using java script.when i enter value and click copy button it dynamically generate tables. then i try to insert values in textbox1 and get the value in txtbox2 by clicking get button.but get button onclick function is not working ?

How to add event listener to dynamically added elements, Pure javascript: Adding event handlers to dynamically created elements. In jQuery I If I just use getElementsByClassName and iterate through them it won't work on future elements. 1 addEventListener("click", function(evt) { if (evt.target​  The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Comments
  • google.com/search?q=angular+delegation+site:stackoverflow.com
  • @Suhel Khan if you want to select and addEventListener all <img> you can check my answer
  • Thanks, this is also work, but instead of 'img' target good to send the nativeElement of the required element