简体   繁体   中英

JavaScript error: Uncaught TypeError: Cannot read property 'remove' of undefined

I have a script to remove uploaded files after Add to success, but I get this error on site when it loads.

"Uncaught TypeError: Cannot read property 'remove' of undefined"

What's missing?

<script>
onload=function() {
    document.querySelectorAll("li[id^='uploadNameSpan']")[0].remove();
}
</script>

Basically, your issue is that, at the time you call this code, you don't have any elements in the DOM corresponding to the query "li[id^='uploadNameSpan']" . So querySelectorAll returns an empty NodeList which has undefined at the 0 position (or any position for that matter).

Breakdown of what is happening:

var liElements = document.querySelectorAll("li[id^='uploadNameSpan']"); // this returns an empty NodeList

var nonExistentFirstElement = liElements[0]; // this is undefined, there's nothing at the first position

nonExistentFirstElement.remove(); // thus, this is an error since you're calling `undefined.remove()`

Depending on your use case, one thing you can do is have a check for the amount of items returned before trying to remove:

var liElements = document.querySelectorAll("li[id^='uploadNameSpan']");
if (liElements.length > 0) {
  liElements[0].remove();
}

In general, you have to make sure to have the element in the DOM at the time you are trying to remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM