JS&HTML报错:Cannot read property 'remove' of null 问题求助
Hey there, let's break down exactly why that error is hitting you, and how to fix it.
First, let's recap your code setup:
You're creating an <li> element dynamically:
var entry = document.createElement('li'); entry.appendChild(document.createTextNode(nameChild)); entry.setAttribute('id', idDoChild);
Then you're trying to add a trash icon with a click handler using innerHTML:
cell1.innerHTML = "<img src='assets/trash' width='13px' height='13px' onclick='this.remove(); removeElement(" + idDoChild +")'>"; function removeElement (id){ document.getElementById(id).remove(); }
The Exact Problem
That error happens because of how you're passing idDoChild into the removeElement call in your inline onclick handler.
Element IDs are strings, right? When you concatenate idDoChild directly into the string like that, if your ID was something like child-123, the resulting onclick code becomes:
this.remove(); removeElement(child-123)
Wait a second—child-123 here is being treated as a variable name, not a string! Since there's no variable named child-123 in the global scope when the user clicks the image, removeElement gets undefined as its id parameter.
Then document.getElementById(undefined) returns null (because no element has an undefined ID), and trying to call .remove() on null throws that "Cannot read property 'remove' of null" error.
Easy Fixes
1. Wrap the ID in quotes when concatenating
You need to make sure the ID is passed as a string literal. Escape single quotes (or use double quotes) to wrap idDoChild:
// Escape double quotes since the outer string uses them cell1.innerHTML = "<img src='assets/trash' width='13px' height='13px' onclick='this.remove(); removeElement(\"" + idDoChild +"\")'>";
If you can use ES6 template literals, this is way cleaner:
cell1.innerHTML = `<img src='assets/trash' width='13px' height='13px' onclick='this.remove(); removeElement("${idDoChild}")'>`;
2. Ditch inline handlers entirely (better practice)
Inline event handlers can cause scope headaches and are harder to maintain. Instead, create the image dynamically and attach the handler with addEventListener:
const trashImg = document.createElement('img'); trashImg.src = 'assets/trash'; trashImg.width = 13; trashImg.height = 13; trashImg.addEventListener('click', function() { this.remove(); removeElement(idDoChild); }); cell1.appendChild(trashImg);
This way, you don't have to mess with string concatenation, and the handler has direct access to the idDoChild variable from the surrounding scope—no more null errors.
内容的提问来源于stack exchange,提问作者Bny4W

