My html code contains a <ul id="users"></ul>, which is then populated dynamically with JS code
const li = document.createElement("li");
li.appendChild(document.createTextNode(`${nameInput.value} : ${emailInput.value}`)
I added a button in the html code to delete all users in that <ul>,as such: <button class="btn" id="del-user-list" onClick="deleteUserList()">Delete User List</button>.
My deleteUserList function in the JS code looks like this:
function deleteUserList() {
while (userList.firstChild != "") {
userList.firstChild.remove();
}
}
This works on the surface, however I realize that after the last child, my function will check once again for the value of a child that doesn’t exist. I remember from studying C and playing with linked lists that you don’t want to dereference a pointer that points to null.
Sure enough, when I look at the console I get
Uncaught TypeError: Cannot read properties of null (reading 'remove') at deleteUserList (main.js:31:25) at HTMLButtonElement.onclick ((index):29:77)
Is this a problem and what can I do about it? I just started playing with Javascript and don’t have a good sense of how those things work right now.
>Solution :
Instead of comparing userList.firstChild to an empty string, you should compare it against null or omit the comparison operator entirely:
while (userList.firstChild != null)
// or
while (userList.firstChild)
The latter one works because converting null to a boolean value returns false
null != '' will always be true because userList.firstChild will never be an empty string anyway. It will either be a DOM node or null.