Search code examples
javascripthtmlremovechildhtmlcollection

childNodes is 0 but I have children


I have the following HTML. Using JS, I have a HTMLcollection of slot. And then I am trying to remove the child <p> for a given slot. But the JS console is throwing an error that there is no child. Is it because I have a HTMLCollection?

const slots = document.getElementsByClassName('slot');

for (let i = 0; i < slots.length; i++) {
  slots[i].addEventListener('dragover', () => {
    const dragging = document.querySelector('.card-dragging');
    slots[i].appendChild(dragging);
    slots[i].removeChild(slots[i].lastChild);
  })
};
<section class="slots">
  <div class="slot">
    <img id="rabbit" src="https://gravatar.com/avatar/c331326b84b173e6fb0ddaefd8520044?s=400&d=retro&r=x" alt="rabbit" />
    <p class="card-slot card-temp"></p>
  </div>

  <div class="slot">
    <img id="ball" src="https://gravatar.com/avatar/c331326b84b173e6fb0ddaefd8520044?s=400&d=retro&r=x" alt="ball" />
    <p class="card-slot card-temp"></p>
  </div>

  <div class="slot">
    <img id="book" src="https://gravatar.com/avatar/c331326b84b173e6fb0ddaefd8520044?s=400&d=retro&r=x" alt="book" />
    <p class="card-slot card-temp"></p>
  </div>
</section>


Solution

  • Your code can benefit from Delegation

    You cannot remove the child in the middle of dragging, I expect you want to hide and move it back outside when you drop?

    I could not find the .card-dragging so I guessed

    const slots = document.querySelector('.slots');
    slots.addEventListener('dragover', (e) => {
      const tgt = e.target.closest('div.slot');
      if (!tgt) return;
      const dragging = document.querySelector('.card-dragging');
      tgt.appendChild(dragging);
    })
    img {
      height: 50px;
    }
    
    .slot { border: 1px solid black; }
    <section class="slots">
      <div class="slot">
        <img id="rabbit" src="https://gravatar.com/avatar/c331326b84b173e6fb0ddaefd8520044?s=400&d=retro&r=x" alt="rabbit" />
        <p class="card-slot card-temp"></p>
      </div>
    
      <div class="slot">
        <img id="ball" src="https://gravatar.com/avatar/c331326b84b173e6fb0ddaefd8520044?s=400&d=retro&r=x" alt="ball" />
        <p class="card-slot card-temp"></p>
      </div>
    
      <div class="slot">
        <img id="book" src="https://gravatar.com/avatar/c331326b84b173e6fb0ddaefd8520044?s=400&d=retro&r=x" alt="book" />
        <p class="card-slot card-temp"></p>
      </div>
    </section>
    <div class="card-dragging">Drop?</div>