the teacher asked us to design a website to teach children letters, when I click the generate button, it generates letters in a random way, and when I click on a letter, an image of something that starts with this letter is displayed. The problem is when I click on another letter, it displays an image of something that starts with this letter, but The old image of the other letter is still present on the page and is not deleted. What I want is when I click on a letter it displays an image of something that begins with this letter and when I click on another letter I want it to delete the old image and display only the image that begins with this letter
this is my JS code
var div2 = document.getElementById("div2");
var div3 = document.getElementById("div3");
var generate = document.getElementById("generate");
var input = document.getElementById("input");
var letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
// here to add the path of the each img to array to store it becuase we will need it leter
litterImg = [];
for (let i = 0;i < 26;i++) {
litterImg[i] = 'img\'+i+'.jpg';
};
var randomLetter = [];
var getRandomLetter = [];
var linkImg = [];
var numberOfLitters;
generate.addEventListener("click",function(e){
numberOfLitters = input.valueAsNumber;
for (let index = 0; index < numberOfLitters; index++) {
let x = randomNumbers();
randomLetter[index] = document.createElement("input");
randomLetter[index].setAttribute("type","button");
randomLetter[index].setAttribute("value",letters[x]);
randomLetter[index].setAttribute("id", x);
randomLetter[index].setAttribute("class",x);
div2.appendChild(randomLetter[index]);
}});
// event to add the images when i click on a litter
div2.addEventListener("click",function(e){
for (let index = 0; index < 26; index++) {
if (e.target.id == index) {
linkImg[index] = document.createElement("img");
linkImg[index].setAttribute("src",litterImg[index]);
linkImg[index].setAttribute("width","1080px");
linkImg[index].setAttribute("height","720px");
div3.appendChild(linkImg[index]);
}
}
});
and this is my html code
<html>
<head>
<meta>
<title>Alphabet Learner</title>
</head>
<body>
<div id="div" class="div" style="text-align : center;">
<h1>Learn the English Litters </h1><br>
<label >Number of Litters: </label>
<input type="number" class="input" id="input" >
<input type="button" class="generate" id="generate" value="Generate">
<br><br>
<div id="div2" class="div2">
</div><br>
<div id="div3" class="div3"></div>
</div>
<script src="script.js"></script>
</body>
</html>