0
0
Svelteframework~5 mins

svelte:fragment for grouping

Choose your learning style9 modes available
Introduction

The svelte:fragment tag lets you group multiple elements together without adding extra HTML tags to the page.

When you want to return multiple elements from a component without wrapping them in a div or other container.
When you need to pass multiple elements as a single block to a slot or another component.
When you want to organize your template code clearly without affecting the HTML structure.
When you want to conditionally render multiple elements together without extra wrappers.
Syntax
Svelte
<svelte:fragment>
  <!-- multiple elements here -->
</svelte:fragment>
The svelte:fragment does not create any extra HTML element in the output.
It is useful for grouping elements logically in your Svelte code.
Examples
Groups two paragraphs without adding extra HTML tags.
Svelte
<svelte:fragment>
  <p>First paragraph</p>
  <p>Second paragraph</p>
</svelte:fragment>
Passes multiple elements as a single block to a component slot.
Svelte
<MyComponent>
  <svelte:fragment>
    <h1>Title</h1>
    <p>Description here.</p>
  </svelte:fragment>
</MyComponent>
Sample Program

This example shows how svelte:fragment groups a heading and paragraph inside an if block without adding extra HTML elements.

Svelte
<script>
  let show = true;
</script>

{#if show}
  <svelte:fragment>
    <h2>Welcome!</h2>
    <p>This is grouped without extra divs.</p>
  </svelte:fragment>
{/if}
OutputSuccess
Important Notes

Using svelte:fragment helps keep your HTML clean and semantic.

It is especially useful when you want to avoid unnecessary wrappers that might affect styling or layout.

Summary

svelte:fragment groups multiple elements without adding extra HTML tags.

Use it to keep your markup clean and pass multiple elements as one block.

It works well inside conditionals and slots.