Dynamically add images with Javascript

Asked

Viewed 767 times

1

How to add an image dynamically inside this div javascript ?

div class="toad" id="mushs">
    <img id="image" src="mush.png">
</div>

2 answers

3

Beyond the createElement, demonstrated in another answer, there’s the builder Image, unique to create elements imgHTMLImageElement.

const button = document.querySelector('button');
button.addEventListener('click', appendImage);

function appendImage() {
  const div = document.querySelector('#images');
    
  const image = new Image(200, 200); // Largura (width) e altura (height).
  image.src = 'https://i.stack.imgur.com/KPUgS.png';
    
  div.appendChild(image);
}
<button>Criar Imagem</button>
<div id="images"></div>

The builder Image is similar to API document.createElement('img'), but accepts as arguments the width and height of the image.

3


To create elements dynamically in Javascript, just use the function createelement passing the name of the tag you want to create as argument (in this case it is the tag <img>).

After you have created the image element, set in the attribute src the image path and add the element you created inside the div with the appendchild. See the example below:

function criaImagem(){
    const div = document.getElementById("imagens");
    
    const image = document.createElement("img");
    image.src = prompt("Digite o nome ou link da imagem: ");
    
    div.appendChild(image);
}
<div id="imagens"></div>
<button onclick="criaImagem();">Criar Imagem</button>

  • 4

    It’s not good to forget to use one let or const when declaring variables... :)

  • Costume of Python kkkk

  • I created a button to add an image using your code as backup but it is not working (the image is in the same folder as the js file) Function addImg() { const image = Document.createelement('img'); image.src = 'mush.png'; Document.getElementById('mushs'). appendchild('image'); }

  • @Douglaskramer the problem is that you are passing a string in the method appendChild and not your image.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.