Skip to main content

How to Create an Image Element in JavaScript

Dynamically creating <img> elements is a fundamental task for building interactive web pages, such as image galleries, profile picture uploaders, or lazy-loading content. The process involves creating the element in memory, configuring its essential attributes like src and alt, and then appending it to the DOM.

This guide will teach you the standard and most effective methods for creating and configuring image elements. You will learn the best practices for setting attributes, handling load and error events, and using modern JavaScript for a cleaner, more declarative setup.

The Core Steps: Create, Configure, Append

The process for creating any DOM element, including an image, follows three basic steps:

  1. Create: Use document.createElement('img') to create a new <img> element that exists only in memory.
  2. Configure: Set its properties, such as src, alt, className, and styles.
  3. Append: Add the fully configured element to the document using a method like appendChild() or append().

Setting the Essential src and alt Properties

Every image element requires a src (source) attribute to specify the image URL and an alt (alternative text) attribute for accessibility.

For example, you need to create a new image and set its source and alt text.

The most idiomatic way to set standard attributes is to set them directly as properties on the element object.

// 1. Create the element
const myImage = document.createElement('img');

// 2. Configure its properties
myImage.src = 'https://example.com/placeholder/150';
myImage.alt = 'A 150x150 placeholder image';
myImage.title = 'This is a placeholder'; // Add a tooltip

// 3. Append to the DOM
document.body.appendChild(myImage);
note

While image.setAttribute('src', '...') also works, direct property assignment (.src, .alt) is generally preferred for standard attributes as it's more concise and works directly with the DOM object model.

Handling Image Load and Error Events

A robust implementation should handle what happens if the image fails to load. The onerror and onload events are essential for this.

  • onerror: Fires if the image at the specified src cannot be loaded (e.g., due to a 404 error or a network issue).
  • onload: Fires when the image has successfully loaded.

This is crucial for providing a good user experience by avoiding broken image icons.

const myImage = document.createElement('img');
myImage.src = 'https://example.com/path/to/non-existent-image.jpg';
myImage.alt = 'My Image';

// Handle the error case
myImage.onerror = function() {
console.error('Image failed to load.');
// Optionally, set a fallback image
this.src = 'images/fallback-placeholder.png';
// Or hide the broken image
// this.style.display = 'none';
};

// Handle the success case
myImage.onload = function() {
console.log('Image loaded successfully!');
};

document.body.appendChild(myImage);
warning

Warning: Ensure your fallback image path is valid, or you could cause an infinite error loop.

For a cleaner and more declarative approach, you can use Object.assign() to set multiple properties on the new element at once.

Solution:

const image = Object.assign(document.createElement('img'), {
src: 'https://example.com/placeholder/150',
alt: 'A placeholder image',
className: 'thumbnail-image', // Use `className` to set the class
onload: () => console.log('Image loaded!'),
onerror: () => console.error('Image failed!'),
});

// You can also assign styles separately
Object.assign(image.style, {
border: '2px solid blue',
borderRadius: '8px',
});

document.body.appendChild(image);
note

This pattern is the recommended best practice as it cleanly separates creation from configuration and is highly readable.

Practical Example: A Reusable Image Creation Function

You can encapsulate the Object.assign() pattern into a helper function to make creating images throughout your application simple and consistent.

/**
* Creates an <img> element with specified properties.
* @param {object} props - An object of properties to assign to the image.
* @returns {HTMLImageElement}
*/
function createImage(props) {
return Object.assign(document.createElement('img'), props);
}

// Example Usage:
const avatar = createImage({
src: 'images/avatars/user-1.png',
alt: 'User Avatar',
className: 'avatar',
width: 50, // Sets the width attribute
height: 50, // Sets the height attribute
});

document.getElementById('profile-section').appendChild(avatar);

Conclusion

Creating an image element in JavaScript is a simple process that can be made robust and elegant with modern techniques.

  • Always start by creating the element with document.createElement('img').
  • Set essential properties like .src and .alt for functionality and accessibility.
  • Implement the onerror event handler to gracefully manage broken images.
  • The recommended best practice for configuring the element is to use Object.assign() for a clean, declarative setup.