Svelte.js 3 The 'this' Binding Tutorial

In this tutorial we learn how to access DOM nodes directly from within Svelte with the 'this' binding.

We cover how to get and use a reference to a DOM element.

Lesson Video

If you prefer to learn visually, you can watch this lesson in video format.

Lesson Project

If you want to follow along with the examples in this lesson, you’ll need a Svelte app that was cloned with degit or scaffolded with Vite

If you already have an app from previous lessons, you can use that instead.

What is the 'this' binding?

The this binding makes it possible to access DOM nodes directly from within Svelte.

tip If you’re familiar with Vue or React, the this binding is similar to Refs.

For example, let’s say we have an input field with some data as its default value. We want the user to be able to click a button to copy the contents of the field.

To be able to access and manipulate the input, we need a reference to it. The this binding gives us that reference.

How to get a DOM element reference with 'this' in Svelte

To get a reference to a DOM element, we bind to the this binding on the element we want to reference and store that reference in a variable.

Syntax: this binding
<script>
  let referenceVariable
</script>

<element bind:this={referenceVariable} />

To demonstrate, we’ll create the example from earlier. We’ll use the Clipboard API to copy the input field value.

Example: src/App.svelte
<script>
  let inputRef

  async function copyLink() {
    // use the reference to "select" the input
    inputRef.select()
    // then copy the input field "value"
    // to the user's clipboard
    await navigator.clipboard.writeText(inputRef.value)
  }
</script>

<!-- get the reference with "this" and store it in "inputRef" -->
<input bind:this={inputRef} value="https://www.koderhq.com" />
<button on:click={copyLink}>Copy</button>

If we run the example in the browser and click on the button, the url will be copied to the clipboard.

tip The this binding applies to every element and component.