Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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>
like image 533
Ronni Avatar asked May 20 '26 03:05

Ronni


1 Answers

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.

like image 192
nem035 Avatar answered May 21 '26 15:05

nem035



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!