Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manipulate DOM using Svelte framework

Tags:

dom

svelte

I'm pretty much new to Svelte framework. Recently I'm playing around with Svelte but confused how I would manipulate the DOM like in jQuery using Svelte.

I'm trying to show/hide an <li> on button click.

like image 856
rabin Avatar asked Oct 20 '25 08:10

rabin


1 Answers

In Svelte, and other state-driven UI frameworks, you very rarely manipulate the DOM. Instead, you essentially tell the framework what the DOM should look like for some given data, and let it figure out all the details.

So to show or hide elements in response to a button click, you'd do something like this (REPL link):

<button on:click='set({ visible: !visible })'>toggle visibility</button>

{{#if visible}}
  <p>hello!</p>
{{/if}}

Or, if you want to keep the element in the DOM but make it hidden (REPL link):

<button on:click='set({ visible: !visible })'>toggle visibility</button>

<p hidden='{{!visible}}'>hello!</p>

This is much better than manually manipulating the DOM, because you can change all the details — what kind of element it is and therefore what jQuery selector you'd use to target it, whether there are other things that also need to change based on visible, etc — without having to rewrite all your code.

like image 72
Rich Harris Avatar answered Oct 23 '25 14:10

Rich Harris