0
0
Svelteframework~5 mins

svelte:element for dynamic tags

Choose your learning style9 modes available
Introduction

The svelte:element tag lets you create HTML elements dynamically. This means you can choose which tag to use while your app runs, not just when you write the code.

You want to show different HTML tags based on user choices.
You need to build a component that can render as a button, link, or div depending on context.
You want to reuse code but change the tag type without repeating code.
You are building a UI library where users pick the tag type.
You want to keep your code simple by avoiding many if-else blocks for tags.
Syntax
Svelte
<svelte:element this={tagName} {...props}>Content</svelte:element>

The this attribute sets which HTML tag to render.

You can pass other attributes or event handlers as usual.

Examples
This renders a <button> with text 'Click me'.
Svelte
<script>
  let tagName = 'button';
</script>

<svelte:element this={tagName}>Click me</svelte:element>
This renders a link (<a>) that opens in a new tab.
Svelte
<script>
  let tagName = 'a';
  let href = 'https://example.com';
</script>

<svelte:element this={tagName} href={href} target="_blank">Visit</svelte:element>
This renders a <section> with accessible label and nested content.
Svelte
<script>
  let tagName = 'section';
</script>

<svelte:element this={tagName} aria-label="Main section">
  <p>Section content</p>
</svelte:element>
Sample Program

This example shows a box that changes its HTML tag between div and button when clicked. The text updates to show the current tag. The style and click event work on both tags.

Svelte
<script>
  import { onMount } from 'svelte';
  let tag = 'div';
  let count = 0;

  function toggleTag() {
    tag = tag === 'div' ? 'button' : 'div';
  }

  onMount(() => {
    console.log(`Initial tag is: ${tag}`);
  });
</script>

<svelte:element this={tag} on:click={toggleTag} style="cursor: pointer; padding: 1rem; border: 1px solid #ccc; display: inline-block;">
  Click me to toggle tag (currently: {tag})
</svelte:element>
OutputSuccess
Important Notes

Remember to use valid HTML tags in the this attribute to avoid errors.

You can pass any attributes or event handlers to svelte:element just like normal elements.

Using svelte:element helps keep your components flexible and reusable.

Summary

svelte:element lets you pick the HTML tag dynamically.

Use the this attribute to set the tag name.

This helps make flexible and reusable components without repeating code.