There are two ways to create an <img>
element (which is represented by the HTMLImageElement
interface) in vanilla JS.
The document.createElement() method
The most well-known way to create an <img>
element is to invoke the document.createElement()
method:
const img = document.createElement("img");
img.src = "cat.jpeg";
img.alt = "A grey cat with bright blue eyes looks up at the viewer.";
The Image() constructor
A more obscure way to create an <img>
element is to invoke the Image()
constructor:
const img = new Image();
img.src = "cat.jpeg";
img.alt = "A grey cat with bright blue eyes looks up at the viewer.";
Which approach should you use?
This is debatable. Neither approach is inherently better, so it's up to you!
Consistency
One might argue that, because the document.createElement()
method can be used to create any element, it's more 'standard'. You might value this consistency in your codebase.
Specificity
On the other hand, where a more specific API does exist, you might prefer to use it. Another example would be the src
and alt
properties of the HTMLImageElement
interface. You could set these using the more 'standard' .setAttribute()
method, but you might prefer the more specific API.