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?
Add a comment
|
2 Answers
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
usedirective, this will also get you access to the raw DOM node
<script>
function ninja(node) {
node.innerHTML = "Kawabunga!"
}
</script>
<div use:ninja/>
Comments
I would look at the <svelte:self> element, which allows you to create elements that call themselves recursively.