skip to Main Content

I am trying to convert tableBody.children (HTMLCollection) into an array so that I can loop through it. To do this I am using Array.from(tableBody.children and assigning it to a variable, tableChildren.

The problem is when I call the variable it return an empty array. The thing that confuses me is that in the variable when I remove the Array.from method and just have const tableChildren = tableBody.children, it returns the full HTMLCollection intact, but when I put back the Array.from into the variable, it turns into an empty array.

Here is the full block of code:

function editFormSubmit(tableBody) {
    const dogForm = document.getElementById("dog-form");

    // variable in question
    const tableChildren = Array.from(tableBody.children);

    dogForm.addEventListener("submit", event => {
        event.preventDefault();

        const updatedDog = {
            name: event.target[0].value,
            breed: event.target[1].value,
            sex: event.target[2].value
        }

        fetch(`http://localhost:3000/dogs/${event.target[3].value}`, {
            method: "PATCH",
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json"
            },
            body: JSON.stringify(updatedDog)
        })
        .then(res => res.json())
        .then(dog => {
            tableBody.textContent = "";
            getDogs(tableBody);

            // where I am calling the variable
            console.log(tableChildren);
        })
        .catch(err => console.log(err))
        
        
    })
}

Any ideas of what I am doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    So, I figured out the issue. It was tableBody.textContent = "". I forgot to remove it from a previous version of I what I was trying to do.

    Array.from(tableBody.children) was converting nothing since I had emptied out all the table data. Removing tableBody.textContent = "" fixed the issue and I was able to get the HTMLCollection to convert to an array.


  2. An HTMLCollection is live – it is automatically updated when you add children to the tableBody element.

    In contrast, if you convert the HTMLCollection to an array, that array reflects the children only at that exact point in time.

    Therefore, the problem must be that you’ve added children to tableBody after the line of code that converts its children to an array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search