on:click doesn't work when the DOM is updated in Svelte

Viewed 41

The send_random() doesn't work when I added it as a directive in the newly added DOM.

        ...
            for (let i = 0; i < items.length; i++) {
                data = `
                    <div class = "block received">
                        <span class = "item-text">
                            <button type = "submit" on:click = ${send_random}>
                                ${items[i]['text']}
                            </button>
                        </span>
                    </div>
                `;  
         ...

Your help is much appreciated, thank you.

1 Answers

You cannot add Svelte code like that.

It has to be added as part of the template (i.e. not in the script) to be compiled properly.

In general you should not manipulate DOM like that. Add data to lists/set local state and then use {#if}/{#each} to build the DOM.

Related