Removing all items from an element

According to this: https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild

If I want to eliminate all children, I have to do something like this:

Using that approach –

<table id="rankings-table">
        <thead>
            <tr>
                <th>Ranking</th>
                <th>Full Name</th>
                <th>Points</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Steven</td>
                <td>2019</td>
            </tr>
            <tr>
                <td>2</td>
                <td>John</td>
                <td>2001</td>
            </tr>
        </tbody>
</table>

// Javascript
const rankingsBody = document.querySelector("#rankings-table > tbody");
const rows = rankingsBody.firstChild;

            // Clears out existing data
            while (rows) {
                console.log(rankingsBody.removeChild(rows));
            }
            console.log(json);

How come it does not remove all children when storing the firstChild as a variable, rows? Can someone explain friendly and thoroughly?

What does while(rows) exactly mean here? If “rows” never changes, shouldn’t loop the break once the first child is no longer a “textNode”? How come
while (rows) {
console.log(rankingsBody.removeChild(rankingsBody.firstChild));
}
this works tho?

1 Like

Your function is not removing anything, is just logging into the console they hypothetical result of that operation, but never executes it.

This because the removeElement part is inside a console.log().

Also please consider that your function has a major difference from the original example.

The original exemple select the parent and loop on the condition that firstChild exists.

Your version select the first child, this means that you need to update yourself the new firstChild

Hope this helps :+1: