0

I am using the software Brackets for coding JavaScript. And I came across this

var value = document.getElementById(id).files[0] 

I was wondering if anyone could explain what its function is and how I could possibly use it in the future and what is the significance of .file[0]

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Jem Stone
  • 13
  • 3
  • Are you only asking about `files`? The rest is common Javascript and is covered in many tutorials. Just search for the method name. – Carcigenicate Nov 26 '17 at 01:44

3 Answers3

0

From the HTML5 specification on Forms Section 4.10.5.4:

The files IDL attribute allows scripts to access the element's selected files. On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files. The same object must be returned until the list of selected files changes. If the IDL attribute does not apply, then it must instead return null.

Basically .files returns a list (FileList) of selected files that scripts can access.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

According to W3Schools, the files property returns a FileList object, representing the file or files selected with the file upload button.

Through the FileList object, you can get the name, size and the contents of the files

This property is read-only. You can read more about it on W3schools website here

You can also learn how to use it here

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
0

document.getElementById(id) will give you a normal JS object which can have both properties (or attributes) and methods. First, the instruction that you're asking for is expecting this object to have a "files" property.

Properties in javascript can be primitives (as string, number or boolean), complex objects and arrays.

In this case, the brackets are giving us a hint that this property (files) is an array. Array elements are accessed by an index inside the brackets. .files[0] represents the first item inside this array.

For example, if you have an array like:

var myArray = ['first', 'second', 'last']

You can access the elements with the same syntax you're asking for:

myArray[0]  //first
myArray[1]  //second
myArray[2]  //last

Without knowing the context of your instruction, this files property matches perfectly with a FileUpload input control. Check it here: https://www.w3schools.com/jsref/dom_obj_fileupload.asp

zameb
  • 705
  • 11
  • 26