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);
}
3
Answers
There are a few issues:
liElement
will get only oneli
element, not all of them, so you cannot expect themouseout
handler to remove all of them.topicsDiv
is not the parent ofliElement
, sotopicsDiv.removeChild(liElement)
will not work — it will actually trigger an error which you should see in the console.In the
mouseover
handler you have a typo:topiclUl
is nottopicUl
. Also this should lead to an error message in the console.To fix this you could iterate over all
li
elements to delete them one by one, but it is much easier to just clear the content in theul
element, so just do:Your code has a couple of issues that need to be addressed. Here’s the corrected version:
Changes made:
topiclUl
totopicUl
in the loop where you areappending
li
elements.i < stringsArray.length
to prevent accessing an undefined element in the array.while
loop to remove all child elements of theul
when the mouse leaves thediv
.This should resolve the issue of infinite li elements being created and not being removed when not hovering.