I’m trying to create a web page where, on button push, a random image is loaded into a div. I can get the random image to load to the page, but it appears below the div instead of inside it.
(I see there are many other similar questions here, I’ve looked at quite a few but the solutions don’t seem to work for me. Not sure what I’m misunderstanding.)
This is the script I put in the header section of my html page:
<script type="text/javascript">
function display_random_image()
{
var theImages = [{
src: "tarot/1.png",
}, {
src: "tarot/2.png",
},
];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
}
// create random image number
function getRandomInt(min,max)
{
// return Math.floor(Math.random() * (max - min + 1)) + min;
imn = Math.floor(Math.random() * (max - min + 1)) + min;
return preBuffer[imn];
}
// 0 is first image, preBuffer.length - 1) is last image
var newImage = getRandomInt(0, preBuffer.length - 1);
// remove the previous images
var images = document.getElementsByTagName('img');
var l = images.length;
for (var p = 0; p < l; p++) {
images[0].parentNode.removeChild(images[0]);
}
// this displays the image below the div tag
document.body.appendChild(newImage);
}
</script>
This is the HTML
</head>
<body >
<div class = "placehere">
</div>
<button id="jsstyle"
onclick="display_random_image();">Show Image</button>
</body>
I’ve tried using this for the final line of the javascript instead:
document.getElementById("placehere").appendChild(newImage);
But it doesn’t work.
>Solution :
placehere is a class not an id, so you can’t use getElementById to get it.
You can change it from a class to an id which will get it to work or you can use getElementsByClassName which returns a list of elements
<div id="placehere"></div>
document.getElementById("placehere").appendChild(newImage);
<div class = "placehere"></div>
document.getElementsByClassName("placehere")[0].appendChild(newImage);