Q:

JavaScript API to create Svelte elements instead of a template

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?

A:

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

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}/>

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/>

