Ilmiont Ilmiont - 8 months ago 16
Javascript Question

Why specify [0] when using new FormData()?

I've just spent a good few minutes debugging

why new FormData($("#ImageEditorForm"));
isn't working. After turning to Stack Overflow, I found a suggestion in another thread to use
new FormData($("#ImageEditorForm")[0]);

I made the change, not expecting anything to happen. Instead, the code now works perfectly and as expected. Previously, nothing was being submitted to the server. Now, form data and files appear as expected.

My question is why is the "[0]" required? There is only one element with that ID in the DOM. Selecting by ID should surely return only one element? What is going on here?


$("#ImageEditorForm") returns a jQuery object and FormData requires a DOM Node.

You can use document.getElementById(id); which returns a DOM Node.


Or use document.querySelector(selector); which takes a css selector and returns the node if found and null otherwise.