user18752895
user18752895

Reputation:

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

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.

Upvotes: 2

Views: 257

Answers (2)

zibi
zibi

Reputation: 1

I had the same problem. Reactively creating the variables solved my problem, you can try it too.

let variable = "..."

changed to

$: variable = *some queries or logics*

Upvotes: 0

brunnerh
brunnerh

Reputation: 184516

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.

Upvotes: 2

Related Questions