'How to use children/slot string inside script tag in svelte

There is some way of use the slot content inside the script tag? something like this:

<CustomComponent>I want to use this text inside the script tag of the custom component</CustomComponent>

and inside the custom component:

<script>console.log(ThatOneString)</script><slot/>



Solution 1:[1]

There is no easy way, in theory a slot can contain 'whatever', strings, html, other components, ... and the most common attitude is "Here is place to something, I don't actually care what you put here".

This means that the only way of somehow accessing this is to use a wrapping element: ```html

```

and then use good old javascript

let wrapper
$: content = wrapper?.innerHTML
$: console.log(content)

(the ?. part is because wrapper will be initially undefined)

But this will not work with dynamic content, if you want to log this every time the content changes, you will have to start messing around with a MutationObserver to track the slot.

import { onMount } from 'svelte'
let content
let wrapper
    
$: console.log(content)
    
onMount(() => {
  const obs = new MutationObserver(() => content = wrapper.innerHTML)
  obs.observe(wrapper, { characterData: true, subtree: true })
  return () => obs.disconnect()
})

at which point I would start wondering if using slots was the correct approach :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephane Vanraes