Loading multiple images through Javascript

5

I'm trying to upload an image through Javascript but it did not work. In the HTML it looks like this: <img src="img/bola.jpg/> , but in Javascript I do not know.

The code below is to show loading of several images, but I do not know why it is not loading:

Follow the Javascript:

/*
autor : Jose Lemo
descricao: Estudo cinema da baladinha
*/

// true = disponivel, false = indisponivel

window.onload = function(){
    carregarPoltronas(); // não está carregando a imagem
}

var poltronas = [false,true,false,true,true,true,false,true,false];

function carregarPoltronas(){
var imagens = document.getElementsByName("img");

for(var i=0; i<imagens.length;i++){      
    imagens[i].src = "img/disponivel.jpg"; 

    } 
} 

Follow xhtml:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">     
  <head> 
    <title> JavaScript CinemaBaladinha</title>  

    <style>
      div{
        margin:0 auto; width:740px; text-align:center;height:250px;
      }
      #topo {
        background:url(img/baladinha.jpg) no-repeat; 
      }
    </style> 

    <script type = "text/javascript" src = "js/CinemaBaladinha.js"></script> 

  </head>      
  <body>   
    <div id = "topo"></div>

    <div>
      <img />
      <img /> 
      <img /> 
      <img /> 

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

Can someone give me an example of how to load an image with Javascript?

    
asked by anonymous 06.04.2016 / 03:27

1 answer

4

Correct is getElementsByTagName :

var imagens = document.getElementsByTagName("img");

Alternatively you can use querySelectorAll , which is more flexible and would allow you to filter the elements better:

var imagens = document.querySelectorAll("img");

function carregarPoltronas(){
  var imagens = document.querySelectorAll("img");
  for(var i= 0; i < imagens.length; i++){      
    console.log(imagens);
  } 
} 

window.onload = function(){
    carregarPoltronas();
}
<div>
      <img />
      <img /> 
      <img /> 
      <img /> 
</div>
    
06.04.2016 / 04:44