Search code examples
sveltekit

How to access DOM elements and use in function


Consider this code:

<script>
    let input;
    const foo = () => {
        let html = input.innerHTML;
        // Do something with HTML
    }
</script>

<button on:click={foo}>Foo</button>
{#if edit}
    <div bind:this={input}></div>
{/if}

I need to get the DOM Element for the div. Then use it in a function run by the button. How can I do this? bind:this only works in onMount, but I can't define foo inside onMount.

Understand that innerHTML or the specific method/property is not important. I just need the DOM element to use it in a function called when a button is pressed.


Solution

  • The element simply does not exist.

    You have to wait for it to be created in the next update.

    import { tick } from 'svelte';
    async function foo() {
      edit = true; // change #if condition so next update creates element
      await tick();
      // [interact with bound element]
    }
    

    REPL