null error work around.
Im having various event listeners for child class . In HTML there is only parent classes, the child classes are then added via JS, when a page loads im getting null errors for these event listners, how to fix this?
24 Replies
add the listeners after the children are added
thats what i did and i still got this erro
what's on line 507?
this is from line 502, so newCard.addEventListner is where im getting error at
well, newCard must be
null
, which means at the time document.querySelector(".add-card-button ")
runs that's returning nothing
I don't think it's the problem, but that space at the end of the selector looks sloppy
when does the add-card-button
element get added?im adding this around 360.
is that inside a callback and line 500 isn't?
it looks like something that gets added after loading data from a backend maybe?
That space at the end of the selectors is most likely the problem.
I really don't think it is, it should get trimmed. It works in a quick test: https://codepen.io/jochemm/pen/KKGoNbd?editors=1111
there is no backend involved, everything is in object.
this main function is called at the start ie domcontentloaded.
when is the line 500-ish code called? Is it part of the same function? Any promises around either?
i didnt call that, its a part of document flow.
line 300ish is added.
if it's part of the document flow, it's probably running before domcontentloaded is fired
https://codepen.io/avinash-tallapaneni/pen/MWPyvQe this is how i coded
if its running before domcontentloaded wont i get an error before
add-card-button
being added? 🤔the event handler still fires even if there's a null reference error further down in the file
As @jochemm suspected, you are trying to define newCard before it exists in the DOM
but yeah, what you shared would first run lines 147 and onward, and then when the dom is fully loaded later, it runs your eventhandler adding the buttons
Why don't you just have those in the function that adds the buttons in the first place? You replace them entirely, so any old event listener would be discarded anyway
so you are saying i have to add event handlers in the main functions? 🤔 cause these eventhandler has a few operation going on, so i dont want the main function to look messy
you have to add them after the elements you're targeted are added to the dom, whether that's in the main function or in a seperate
setupEventListeners
function, or with separate methods defined outside the main function but then added inside the main function, that's all up to youi moved these into main function, this is working. i probaly have to think about how to push data into array of object without messsing it up
not sure what you mean by the last part, but glad that it works!