Greetings, I am creating a button that shows a random letter in Javascript , but I want to know how I can replace a new letter with the one I had previously in the output div since when activating the button, the new one is created below the previous one. I attach code and thank you in advance for the answers.
<button onclick="sacar();">Sacar carta</button>
<div id="cartaOutput">
Aquí va la imagen de la carta
</div>
<input type="hidden" id="cartaHidden"/> <!--En este input va un valor que es con el que mando llamar a la carta-->
Now goes the Javascript
function sacar()
{
document.getElementById("cartaHidden").value = Math.floor((Math.random()*42)+1); //Genero el número aleatorio
var carta=document.getElementById("cartaHidden").value; //Esto me permite pasar el valor del número random a una variable
var cartaOutput=document.getElementById("cartaOutput");
var salida=document.createElement("IMG");
salida.setAttribute("src", ""+carta+".png");
cartaOutput.appendChild(salida); //Aquí muestro la imagen
}
Try adding a default img element and then modifying its
src
.In html, we indicate the default image:
We set
display:none
it because there is no initial image when it loads the tag and we don't want it to show an error.Now in the js, instead of creating, we look for the image-load element and assign the attribute
src
to it and tell it to show the image already loaded:Example worked: