How to make functions work with newly added HTML via JS?

So, I have normal JS file and a button that adds new HTML when clicked. But my functions that are in the file do not work with newly added element. What am I doing wrong?
8 Replies
13eck
13eckā€¢2y ago
Nothing, that's how it works. JS only knows about elements that are present when the script/function runs. If something's added later it won't know about it. The best practice is to do what's called event delegation: you add your event listeners on a parent div that's already there and have the one event listener delegate the event based on what was done to what element. That way even if you add elements later the parent element will still be there. The other option is that when you add the new elements you have to also add new event listeners on each one. https://gomakethings.com/listening-for-events-on-multiple-elements-using-javascript-event-delegation/
Dovah
DovahOPā€¢2y ago
Roger! Thanks for the info! šŸ˜„
13eck
13eckā€¢2y ago
šŸ‘
Dovah
DovahOPā€¢2y ago
@cvanilla13eck Ok I'm having mad trouble figuring it out... šŸ˜¦ Can I ask you for help here or make a new thread?
13eck
13eckā€¢2y ago
Best to make a new thread, as this one has been answered
Dovah
DovahOPā€¢2y ago
Even though the question is similar? Actually yeah I will, I will just try it a few more times. myself before I wave white flag
13eck
13eckā€¢2y ago
This question has been answered. If you have another question then make another post, please
Dovah
DovahOPā€¢2y ago
Roger!
Want results from more Discord servers?
Add your server