Search code examples
javascripthtmllistappendchild

How to append items from array to list


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);
}


Solution

  • Your code has a couple of issues that need to be addressed. Here's the corrected version:

    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.appendChild(topicUl);
    
        for (let i = 0; i < stringsArray.length; i++) {
            let liElement = document.createElement("li");
            liElement.textContent = stringsArray[i];
            topicUl.appendChild(liElement);
        }
    };
    
    topicsDiv.onmouseout = function() {
        while (topicUl.firstChild) {
            topicUl.removeChild(topicUl.firstChild);
        }
    
        topicsDiv.removeChild(topicUl);
    };
    <!DOCTYPE html>
    <html>
    
    <body>
    <div id="topics-div">Topics</div>
    </body>
    
    </html>

    Changes made:

    • Fixed the typo in topiclUl to topicUl in the loop where you are appending li elements.
    • Changed the loop condition to i < stringsArray.length to prevent accessing an undefined element in the array.
    • Used a while loop to remove all child elements of the ul when the mouse leaves the div.

    This should resolve the issue of infinite li elements being created and not being removed when not hovering.