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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With