1

Svelte’s templating language is great, in that it looks like HTML. However, for highly dynamic content I need to be able to use the full power of JavaScript, not just #if and #each. For example, given a tree data structure, I want to generate hierarchical table headings. (Demo) In React most apps use JSX templates, but you can drop down to createElement if you need to. Is there a similar path for Svelte? Am I missing something obvious?

2 Answers 2

2

If you need access to the DOM node, you can:

  1. Add bind:this={node} to get access to the DOM node:
<script>
    import {onMount} from 'svelte'

    let node

    onMount(() => {
        const dynamic = document.createElement('a')
        dynamic.innerHTML = "Click me!"

        node.appendChild(dynamic)   
    })
</script>

<div bind:this={node}/>
  1. Add a use directive, this will also get you access to the raw DOM node
<script>
    function ninja(node) {
        node.innerHTML = "Kawabunga!"
    }
</script>

<div use:ninja/>
Sign up to request clarification or add additional context in comments.

Comments

0

I would look at the <svelte:self> element, which allows you to create elements that call themselves recursively.

https://svelte.dev/tutorial/svelte-self

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.