Search code examples
htmlfileapi

img element in HTML: file attribute and src attribute behaves differently


I have a file attribute that is saved on a certain <img id = "one"> element. Said file attribute contains an object of File type. I have antother <img id = "two"> element. When I try this:

document.getElementById('two').src = document.getElementById('one').file

it behaves differently with:

document.getElementById('two').file = document.getElementById('one').file

The first line of code returns the string representation of my File contained in img one and the second line of code returns the actual File object. What's with this difference of behaviour?


Solution

  • HTMLImageElements don't have a file attribute, so when you assign document.getElementById('two').file, you're just creating a file property on the JavaScript object representing <img id="two">. Access that property, and you get back the File you put in.

    But document.getElementById('two').src is an IDL attribute that reflects the src content attribute of the img element. The src content attribute contains the address of the image, so when you access the src IDL attribute from JavaScript, you get the file converted to a string:

    2.7.1 Reflecting content attributes in IDL attributes

    Some IDL attributes are defined to reflect a particular content attribute. This means that on getting, the IDL attribute returns the current value of the content attribute, and on setting, the IDL attribute changes the value of the content attribute to the given value.

    [...]

    If a reflecting IDL attribute is a USVString attribute whose content attribute is defined to contain a URL, then on getting, if the content attribute is absent, the IDL attribute must return the empty string. Otherwise, the IDL attribute must parse the value of the content attribute relative to the element's node document and if that is successful, return the resulting URL string. If parsing fails, then the value of the content attribute must be returned instead, converted to a USVString.