How to get html element of Svelte component using bind:this?
Asked Answered
C

1

10

Suppose I have a reusable component called button.svelte,

<script>
export let text = undefined
</script>

<button>{text}</button>

Now I reuse this component in another component like so,

<script>
import { onMount } from "svelte"
import Button from "./Button.svelte"

let button

onMount(() => {
    console.log(button) // How do I print the html of the button element?
})
</script>

<Button text="Button" bind:this="{button}"></Button>

But button of bind:this doesn't seem to have the html of the button element. How do I get the html element of the button?

Culver answered 30/4, 2021 at 13:10 Comment(3)
Did you try innerHTML on button inside console.log? Also bind:this isn't supposed to be without double quotes?Nittygritty
May be this can help : https://mcmap.net/q/1074523/-how-can-i-return-the-rendered-html-of-a-svelte-componentNittygritty
@JulienGabriel I tried doing button.innerHTML but shows undefinedCulver
M
15

To achieve this you have to do 2 things

  • bind element to prop using bind:this={prop}.

  • access the element in the parent component via the bonded prop and the important part is that you must do that in a reactive statement $:.

Button.svelte

<script>
    export let node
</script> 

<button bind:this={node}>
  <slot />
</button>

import Button component

<script>
    import Button from './Button.svelte'
    let button
    
    $:console.log(button)
</script>

<Button bind:node={button}>
    Hello
</Button>
Memberg answered 1/5, 2021 at 5:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.