I have an array "stringsArray" and I need to append all its items to a div as "li" items. That should happen when the person hovers over the div. The "li" elements should also be removed when the div is not being hovered anymore. The problem is that when I hover the div, an infinite number of "li" elements is created. Also, the li elements are not being removed when not hovering. What is wrong with my code?
HTML
<div id="topics-div">Topics</div>
JS
let stringsArray = [
"Topic 1",
"Topic 2",
"Topic 3",
"Topic 4",
"Topic 5"
]
let topicsDiv = document.getElementById("topics-div");
let topicUl = document.createElement("ul");
topicsDiv.onmouseover = function(){
topicsDiv.append(topicUl);
for(i = 0; i <= stringsArray.length; i++){
let liElement = document.createElement("li");
liElement.textContent = stringsArray[i];
topiclUl.appendChild(liElement);
}
}
topicsDiv.onmouseout = function(){
let liElement = topicsDiv.querySelector("li");
topicsDiv.removeChild(liElement);
}
Your code has a couple of issues that need to be addressed. Here's the corrected version:
Changes made:
topiclUltotopicUlin the loop where you are appendinglielements.i < stringsArray.lengthto prevent accessing an undefined element in the array.whileloop to remove all child elements of theulwhen the mouse leaves thediv.This should resolve the issue of infinite li elements being created and not being removed when not hovering.