Ronni
Ronni

Reputation: 195

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>

Upvotes: 9

Views: 82077

Answers (1)

nem035
nem035

Reputation: 35491

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.

Upvotes: 12

Related Questions