How to Create an Image Element using JavaScript?
Last Updated :
09 Jan, 2025
Improve
We will dynamically create an <img> element in HTML using JavaScript. When a button is clicked, we’ll generate the <img> element and append it to the document.
Using createElement() method
- Create an empty img element using document.createElement() method.
- Then set its attributes like (src, height, width, alt, title, etc).
- Finally, insert it into the document.
Example: In this example, we create an image element using JavaScript.
<!DOCTYPE HTML>
<html>
<head>
<title>
How to create an image element
dynamically using JavaScript ?
</title>
</head>
<body id="body" style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on the button to add image element
</h3>
<button onclick="GFG_Fun()">
click here
</button>
<h2 id="result" style="color:green;"></h2>
<script>
let res = document.getElementById('result');
function GFG_Fun() {
let img = document.createElement('img');
img.src =
'https://media.geeksforgeeks.org/wp-content/uploads/20190529122828/bs21.png';
document.getElementById('body').appendChild(img);
res.innerHTML = "Image Element Added.";
}
</script>
</body>
</html>
Output:

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.