why does a html button only generate an ul node once when clicked multiple times?

When you use parentElement.appendChild(element) the existing element is moved from its current location to the new location

The first time, this results in the element being added to the DOM

Second and subsequent calls simply moves the element from its current location in the DOM to the new location – in this case back to where it was, since it already is the last child of document.body


The only time this code could be a problem is if other elements are appended after this UL … in that case, calling createListElem would move the UL element after those elements

One way to avoid this is to check if ul is already in the DOM – i.e. it has a .parentElement (or .parentNode) and only append it if it does not

const ul_node = document.createElement("ul");
function createListElem() {
    if (!ul_node.parentElement) {
        document.body.appendChild(ul_node);
    }
    // ... etc
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top