Question:
I'm trying to load an image through Javascript but it didn't work. In HTML it looks like this: <img src="img/bola.jpg/>
, but in Javascript I don't know.
The code below is to show loading multiple images, but I don't know why it's not loading:
Here's 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";
}
}
Here's the xml:
<!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 anyone give me an example of how to load an image with Javascript?
Answer:
The correct one is getElementsByTagName
:
var imagens = document.getElementsByTagName("img");
Alternatively you could use querySelectorAll
, which is more flexible and would allow you to filter 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>