I am having issues adding a click event listener to elements that are not yet present on the page. Just a note that I am performing the following code within a JQuery equavilant to document ready, so it is performed after the DOM is loaded. So I have a div which I am using as a type of button
<div id="openContainer"> ... </div>
Now when this div is clicked, another div is dynamically added to the page. This div is only added when the above click event takes place. The div that is added has a button with the id search. I am trying to add an event listener to this. So far I have this
document.getElementById('openContainer').addEventListener('click', function() {
document.getElementById('search').addEventListener('click', function() {
alert("ADDED")
});
});
However when I run this I get an error that document.getElementById(...) is null. I think the reason behind this is because the event listener is being added before the actual dynamic div has been added. In fact, I know this is the case because it works with a timeout e.g.
document.getElementById('openContainer').addEventListener('click', function() {
setTimeout(function () {
document.getElementById('search').addEventListener('click', function() {
alert("ADDED")
});
}, 2000);
});
Is there any way I can do this without a timeout?
Thanks