Skip to main content

Part 3 / Special elements / <svelte:element>

Sometimes we don't know in advance what kind of DOM element to render. <svelte:element> comes in handy here. Instead of a sequence of if blocks...

App.svelte
{#if selected === 'h1'}
	<h1>I'm a h1 tag</h1>
{:else if selected === 'h3'}
	<h3>I'm a h3 tag</h3>
{:else if selected === 'p'}
	<p>I'm a p tag</p>
{/if}

...we can have a single dynamic component:

App.svelte
<svelte:element this={selected}>I'm a {selected} tag</svelte:element>

The this value can be any string, or a falsy value — if it's falsy, no element is rendered.

Next: <svelte:window>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script>
	const options = ['h1', 'h3', 'p'];
	let selected = options[0];
</script>
 
<select bind:value={selected}>
	{#each options as option}
		<option value={option}>{option}</option>
	{/each}
</select>
 
{#if selected === 'h1'}
	<h1>I'm a <code>&lt;h1&gt;</code></h1>
{:else if selected === 'h3'}
	<h3>I'm a <code>&lt;h3&gt;</code></h3>
{:else if selected === 'p'}
	<p>I'm a <code>&lt;p&gt;</code></p>
{/if}
 
initialising