How to add an image to the DOM using JavaScript

I need to programmatically add pictures toDOM, In other words, HTML pages.

For this, I created aimgElement usagecreateElementMethods of the Document object:

const image = document.createElement('img')

Then I setsrcPicture attributes:

image.src  = '/picture.png'

(You can use relative or absolute URLs, just like in normal HTMLimglabel)

Then I determined the container to attach the image to, and then I named itappendChild()The method will do:

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

Download mine for freeJavaScript beginner's manual


More browser tutorials: