
How to Execute Code When DOM Element is Created
In Svelte, there is a use:action directive that you can use to run code when an element is created or destroyed.
Copied to clipboard!
<!-- You can use the use:action directive to run code when an element is created or destroyed -->
<script>
export let notif;
const notificationObserver = (node, notif) => {
return {
update(notif) { ... },
destroy() { ... }
};
};
</script>
<Notification use:notificationObserver={notif} />
A couple of things to note:
- You have access to the element with the
node
parameter. - Inside the function, the DOM element is mounted.
- Actions can return an object with an
update
anddestroy
method.
These methods will be called when the node changes or it is removed from the DOM.


Resources:
π More Webtips

Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: