Skip to content

Svelte removes everything from a parent when each blocks array becomes empty. #16567

@HighFunctioningSociopathSH

Description

Describe the bug

I was working on a JS library and ran into an issue where the elements added by this library to the DOM were vanishing for no reason. After testing around, I figured out, when an element is injected into the DOM using pure JS, which is usually done by Vanilla libraries, Svelte will also remove those elements when the array of an each block becomes empty.

Reproduction

<script lang="ts">
  import { onMount} from "svelte";

  let colors = $state(["yellow", "red", "blue"]);

  let divRef: HTMLDivElement;
  onMount(() => {
    if (!divRef) return;
    const newDiv = document.createElement("div");
    newDiv.innerText = "someColor";
    divRef.appendChild(newDiv);
  });
</script>

<button onclick={() => colors.pop()}>remove color</button>
<div bind:this={divRef}>
  {#each colors as color}
    <div>
      {color}
    </div>
  {/each}
</div>

For example, in the above code, I have simulated adding a div with the text of someColor to the div that contains an each block. When you click the button to pop the colors, when the colors array becomes empty, the div containing the "someColor" text will also vanish.
REPO

Logs

System Info

System:
    OS: Windows 11 10.0.26100
    CPU: (16) x64 12th Gen Intel(R) Core(TM) i7-12650H
    Memory: 7.75 GB / 15.63 GB
  Binaries:
    Node: 23.11.0 - C:\nvm4w\nodejs\node.EXE
    npm: 11.4.1 - C:\nvm4w\nodejs\npm.CMD
    pnpm: 10.13.1 - C:\nvm4w\nodejs\pnpm.CMD
  Browsers:
    Edge: Chromium (136.0.3240.64)
    Internet Explorer: 11.0.26100.1882

Severity

blocking all usage of svelte

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions