Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Checking value of child that doesn't exist?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!