The use of .file[0];

Hi guys, I am trying to understand what this line of code actually does in line 3?

var file = document.querySelector(‘input[type=file]’).files[0];

And here is the script file (JS):

function update_image(){//insert image
var img = document.querySelector(‘img’);
var file = document.querySelector(‘input[type=file]’).files[0];
img.src = window.URL.createObjectURL(file);

It looks like it’s doing the following:

  • look through the page for an input of type file
  • from that input, select the first (aka, 0th) File object in the .files array
  • finally, save the File object in a variable called file
1 Like

Thank you tetchi. Much appreciate your “input” - no pun intended.

haha! badumdum tish!

Glad I could help!

1 Like