I recently add an issue when trying to select some buttons that were added dynamically.
I have setup a function that is dynamically adding buttons to the DOM. I initially add it to the page with window.addEventListener. Then I try to select these buttons with a query selector, but it doesn’t work.
Now if I remove the window.addEventListener and just execute directly the callback function, then I can select the button that I just created dynamically.
I’d say that because the callback is wrapped inside of the event listener, it’s actually executed after the rest of JS, but I’m confused as I thought event listener were regular JS, so should be executing at same time.
function render() { /* do stuff */ }
window.addEventListener('DOMContentLoaded', render);
It sets up to run render when DOM is ready and not before. And this is absolutely the correct way to do things in your case. You just need to make sure your query executes also after DOM is ready, not before.
Next snippet would run synchronously and your buttons would be available during the same loop:
In this case render runs immediately and by default returns undefined (because you have not specified any return value). On DOM load, though, nothing will get executed. So as far as the event goes, it would be equivalent of this:
Thx a lot for taking a look, much appreciate you taking the time to look at my code and help me grow!
When checking the answer though, I think I understand the second part but I don’t see how it applies to what I’ve done
window.addEventListener("DOMContentLoaded", function() {
//do stuff to add buttons with innerHTML applied to an existing DOM element
});
//Try and select the buttons that were created once DOM Content is loaded
const buttons = buttonArea.querySelectorAll(".btns");
console.log(buttons); //return empty object while buttons are displayed
However
//do stuff to add buttons with innerHTML applied to an existing DOM element
const buttons = buttonArea.querySelectorAll(".btns");
console.log(buttons); //return an array-like with all buttons while buttons are displayed
With both approach, I can display buttons, but with the first one, I can’t get them. I don’t get why
window.addEventListener("DOMContentLoaded", function() {
console.log('DOMContentLoaded: When do I run?')
});
console.log('Outer scope: When do I run?')
If the Outer scope console.log was trying to query for buttons created inside DOMContentLoaded what would happen?