Can a Svelte component access the DOM element for its slot contents?

Viewed 1040

Let's say I have svelte code like:

<!-- Widget.svelte -->
<div>
    <slot>No video was provided</slot>
</div>

<!-- App.svelte -->
<Widget>
    <video id="example">
    </video>
</Widget>

Within Widget.svelte, is there a good way for me to get a handle on the video DOM element from the parent-supplied slot? (Of course I could pass in a prop like videoElementId="example" from App.svelte, and then do a document.getElementById(videoElementId) inside Widget.svelte -- but this would be working around Svelte's API, rather than within it.)

1 Answers

I'm not aware of a built-in way to get elements placed in a slot, but you could bind to a container element and query its children:

<!-- App.svelte -->
<script>    
    import Slotted from './Slotted.svelte';
</script>

<Slotted>
    <p>
        I'm a paragraph
    </p>
</Slotted>

<!-- Slotted.svelte -->
<script>
    import { onMount} from 'svelte';    
    let container;
    let childContent;
    
    onMount(() => {
        let firstChild = container.children[0];
        childContent = firstChild.textContent;
    });
</script>

<p>
    Child content: {childContent}
</p>
<div bind:this={container}>
    <slot></slot>
</div>
Related