Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

467
Visualizações
How can I render Images with JavaScript into my HTML

I want to render Images with JavaScript into my HTML-File. I can't find the problem, here is my code from the JavaScript and the HTML. Really appreciate when someone can help me.

Than you!

const imgs = [
    "images/p1.jpg",
    "images/p2.jpg",
    "images/p3.jpg"
]

const container = document.getElementById("container")

function renderImages() {
    let getImgs = ""
    for (let i = 0; i < imgs.length; i++) {
        getImgs = `<img scr="${imgs[i]}">`
    }
    container.innerHTML = getImgs
}

renderImages()



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Headline</h1>
    <div id="container">

    </div>


    <script src="index.js"></script>
</body>
</html>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The problem is that you use an equal sign (=) rather than a plus-equal sign (+=). The plus-equal sign will add the text to the variable, while the equal sign will overwrite the variable.

This line:

        getImgs = `<img scr="${imgs[i]}">`

getImgs is being set to the string, the string is not being added to it. You need to change it to something like this:

        getImgs += `<img scr="${imgs[i]}">`

(Notice the plus before the equal sign)

This way, the variable will not be completely changed, rather it will be appended to.

Full code:

const imgs = [
    "images/p1.jpg",
    "images/p2.jpg",
    "images/p3.jpg"
]

const container = document.getElementById("container")

function renderImages() {
    let getImgs = ""
    for (let i = 0; i < imgs.length; i++) {
        getImgs += `<img scr="${imgs[i]}">`
    }
    container.innerHTML = getImgs
}

renderImages()
/* I added css so you can see the images */
img {
  border: 1px solid black;
  width: 20px;
  height: 20px;
  background: linear-gradient(90deg, blue, green);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Headline</h1>
    <div id="container">

    </div>
</body>
</html>

The CSS was added just so you can see where the images are.

about 4 years ago · Juan Pablo Isaza Relatório

0

const imgs = [
    "images/p1.jpg",
    "images/p2.jpg",
    "images/p3.jpg"
]; // list of sources of images to be rendered

const container = document.getElementById("container"); // the element that is going to contain those images

const loadImage = url => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img); // resolve the promise if the image has been successfully loaded
    img.onerror = () => reject(); // else reject the promise
    img.src = url; // set the source only after the event handlers have been set
  });
};

const renderImages = async () => {
   try {
     const loadedImages = await Promise.all(imgs.map(loadImage));
     const frag = document.createDocumentFragment();
     frag.append(...loadedImages);
     container.appendChild(frag); 
   } catch {
     console.error("Couldn't render the images");
   }
};

renderImages();

here the loadImage function is used to load the images and it returns a promise that resolves only when the images have been loaded

then in the renderImages function we await until all the images have been loaded then we append all those images to a document fragment so to reduce the number of dom updates, then finally we append that document fragment to the container.

I hope it helps and please pardon my bad english.

about 4 years ago · Juan Pablo Isaza Relatório

0

With your code, the result is just one image tag(img): result with your code

You must include the innerHTML inside of the loop: InnerHTML inside the loop

And that's all. HTML result

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda