Reputation: 270
I am rendering html data using innerHrml
in my div. Now i want to handle the click events on <a>
tags on the html data. How can i do that?
Upvotes: 2
Views: 1838
Reputation: 395
You will need to use event.target to target the element which is clicked. You will need to bind the function call to an element that already exists in the DOM. E.g.
document.querySelector(".myDiv").addEventListener("click", e => console.log(event.target));
<div class="myDiv"> <!-- existing element //-->
<a href="#">Dynamically generated element</a>
</div>
This is called "event bubbling" You can learn more about it: https://javascript.info/bubbling-and-capturing
Upvotes: 1
Reputation: 2068
I am assuming that you are normally handling click events by using the onclick
attribute of the HTML <a>
tag. The other method is to just use document.getElementById("theId")
and the addEventListener
method.
var start = document.getElementById("start");
var dynamicDiv = document.getElementById("dynamicDiv");
start.addEventListener("click", function(){
dynamicDiv.innerHTML = '<a id="new">Test this a tag by clicking it.</a>';
var newTag = document.getElementById("new");
newTag.addEventListener("click", function(){
console.log("The <a> tag was clicked.");
});
});
<button id="start">Click to dynamically display data</button>
<div id="dynamicDiv"></div>
Upvotes: 0