Load and append images to DOM with JavaScript/jQuery
This post will discuss how to load and append images to the DOM in JavaScript and jQuery.
1. Using JavaScript
In pure JavaScript, you can use the Image constructor to programmatically create an image with necessary attributes and append it to a DOM container using the Node.appendChild() method.
JS
|
1 2 3 4 5 |
var url = 'https://avatarfiles.alphacoders.com/822/82242.png'; var image = new Image(); image.src = url; document.getElementById('container').appendChild(image); |
HTML
|
1 |
<div id="container"></div> |
2. Using jQuery
With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the .append() method. This is demonstrated below:
jQuery
|
1 2 3 4 5 6 |
var url = 'https://avatarfiles.alphacoders.com/822/82242.png'; $(document).ready(function() { var image = new Image(); image.src = url; $('#container').append(image); }); |
HTML
|
1 |
<div id="container"></div> |
Here’s an alternate version using the appendTo() method, which is similar to the append() method but has a different syntax w.r.t the placement of the content and target.
jQuery
|
1 2 3 4 5 |
var url = 'https://avatarfiles.alphacoders.com/822/82242.png'; $(document).ready(function() { $(`<img src='${url}'>`).appendTo('#container'); }); |
HTML
|
1 |
<div id="container"></div> |
Another plausible way is to use jQuery’s .html() method, as shown below:
jQuery
|
1 2 3 4 5 |
var url = 'https://avatarfiles.alphacoders.com/822/82242.png'; $(document).ready(function() { $('#container').html(`<img src='${url}'>`); }); |
HTML
|
1 |
<div id="container"></div> |
That’s all about loading and appending images to DOM in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)