9

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>
7
  • 1
    Should it not be window.onload ??? Commented Jun 26, 2016 at 20:08
  • 1
    @David This is the same. Commented Jun 26, 2016 at 20:10
  • 1
    Possible duplicate of Uncaught TypeError: Cannot read property 'value' of undefined Commented Jun 26, 2016 at 20:10
  • Nothing matches your selector pattern. Commented Jun 26, 2016 at 20:16
  • Either the selector is wrong...or elements are added after code runs. If it's the latter need to show how they get added. All the explanations why it fails don't get you to solution to make it work Commented Jun 26, 2016 at 20:23

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

5 Comments

this returns [] not really accurate ... is elementList not array
@charlietfl its array-like and irrelevant for this particular problem but you're right. I've actually written that down first and then edited the question to simplify it. Switched it back now.
This seems to work perfect. No script error and functions like it should. Thank you so much
for me, I had to use if( liElements != null ) instead of if(liElements.length > 0)
@PrabuddhaKulatunga that's likely because you used querySelector instead of querySelectorAll

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.