How to add an image to the DOM using JavaScript

By

Learn how to add an image to the DOM with JavaScript by creating an img element with createElement, setting its src, and appending it with appendChild.

~~~

To add an image to a page with JavaScript you create an img element, set its src attribute, and append it to an element already in the DOM. Three steps.

I had the need to do this programmatically, adding an image to the page dynamically at runtime.

First I created an img element using the createElement method of the Document object:

const image = document.createElement('img')

Then I set the src attribute of the image:

image.src = '/picture.png'

(You can use a relative or an absolute URL, just as you’d use in a normal HTML img tag)

Then I identified the container I wanted to append the image to, and I called the appendChild() method on it:

document.querySelector('.container').appendChild(image)

Set the alt text and size

An image created this way is a normal img element, so give it the same attributes you’d write in HTML. The alt text matters for accessibility, and setting width and height reserves the space before the image loads, avoiding a layout jump:

image.alt = 'A sunset over the beach'
image.width = 600
image.height = 400

When does the image load?

The browser starts downloading the image as soon as you set src, even before you append the element to the page.

If you need to run code after the download finishes, for example to read the real dimensions, listen for the load event:

image.addEventListener('load', () => {
  console.log(image.naturalWidth) //1200
})
image.src = '/picture.png'

I set up the listener before assigning src, so everything is in place before the download starts.

Choosing where to insert it

appendChild() adds the image as the last child of the container. If you want it first, use prepend():

const container = document.querySelector('.container')
container.prepend(image)

For a specific position, insertBefore() lets you pass the child the image should go before.

A pitfall: the container is null

If your script runs before the browser has parsed the HTML, querySelector('.container') returns null, and calling appendChild() on it throws:

Uncaught TypeError: Cannot read properties of null (reading 'appendChild')

The fix is to make sure the script runs after the DOM is ready. Load it with the defer attribute, put the script tag at the end of the body, or wrap the code in a DOMContentLoaded listener:

document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('.container').appendChild(image)
})

Any of the three works. Pick one, not all of them.

~~~

Related posts about platform: