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
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/
Roger!
Thanks for the info!
š
š
@cvanilla13eck Ok I'm having mad trouble figuring it out...
š¦
Can I ask you for help here or make a new thread?
Best to make a new thread, as this one has been answered
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
This question has been answered. If you have another question then make another post, please
Roger!