How can we properly access the DOM element generated by an {#each} loop in Svelte when it is clicked?

Using Svelte's {#each} functionality, I am reactively loading elements in the following way:

{#each $items as item}
    <div>
       <Button on:click={someFunction}>{item.text}</Button> (*)
    </div>
{/each}

(*) a component that forwards its on:click

I am trying to find a way to reference the actual DOM element when calling someFunction by clicking on the created item. Passing the index of the array item to the function does not provide me with a reference to the unique DOM element. How can this be achieved?

Here are the approaches I have attempted so far:

  • on:click={() => someFunction(this)}
    → results in undefined

  • on:click={(el) => someFunction(el)}
    → results in undefined

  • on:click={(e) => someFunction(e)}
    → using e.target returns the clicked button, but accessing the div would require .parentElement, which doesn't seem very Svelte-like.

  • on:click={someFunction} combined with bind:this={anItem} → only returns the last created element in the {#each} block.

Answer №1

If you're looking to isolate the parent division, one way to do it in a simple and basic manner would be to utilize an Array setup such as this:

<script>
   let itemsElements = [];
   const someFunction = (i) => console.log(itemsElements[i]); // <- this is your div
</script>
{#each $items as item, i}
    <div bind:this={itemsElements[i]}>
       <Button on:click={() => someFunction(i)}>{item.text}</Button>
    </div>
{/each}

A more sophisticated approach would involve enclosing <Button> within a higher-level component and extracting the reference from there, using techniques like the context API or a slotted prop.

Answer №2

The issue at hand involves a button within a modal that needs to have the ability to open and close. When clicked, the goal is for it to toggle the "open" class. However, using the class directive causes all buttons/modals generated by {#each} to toggle simultaneously.

This suggests that the incorrect property is being utilized. If there are multiple objects, the state needs to be stored per item, and then used for the class directive.

For example:

{#each $items as item}
    <div>
       <Button on:click={someFunction}>{item.text}</Button>
       <div class="modal" class:open={item.show}>...</div>
    </div>
{/each}

Alternatively, the state can be stored in a separate list or dictionary. It's also possible to extract the content of the {#each} to a component with a local state variable specifically for the open state.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to connect a text box to a nested object in the state of a React component?

Solving a React Debugging Dilemma In my current project, I'm developing an office add-in using a React-based starter kit and TypeScript. Unfortunately, debugging has been a challenge as I am unable to access detailed error messages from React in my s ...

Is there a way to decode/compile/interpret the data within nested HTML tags within my AngularJS directives?

How can I process/compile/resolve the contents of enclosed HTML in my directives. The specific directive being discussed is: angular.module('transclude', []) .directive('heading', function(){ return { restrict: 'E&apos ...

Gathering information from a website where the URL remains constant even after clicking on a specific button

Visit this website for bus tickets: I am working on scraping data related to bus trips from the mentioned site. However, the data I need to scrape depends on the user-selected date in my web application. Does anyone have suggestions on how I can develop ...

Sending personalized list attributes through JSON to JavaScript in ASP.NET

Below is a custom list I created for pagination of my results: public class PagedList<T> : List<T> { public int PageIndex { get; set; } public bool HasNextPage { get; set; } // ... } I aim to pass this list via JSON to the View: ...

Please ensure that all files have finished downloading before proceeding to create the object

Within my Session class, I've been instantiating objects from my Question Class. Within this process, images are being downloaded to a local path. However, the issue arises when my LaTeXDoc class demands that all images are already saved at the time o ...

What are the steps to ensure the effective functioning of my checkbox filter?

Currently, my product list is dynamically created using jQuery. I now need to implement filtering based on attributes such as color, size, and price. I found some code that filters the list items by their classes, which worked perfectly for someone else. ...

Text element in SVG not displaying title tooltip

Looking for a solution to display a tooltip when hovering over an SVG Text element? Many sources suggest adding a Title element as the first child of the SVG element. This approach seems to work in Chrome, but not in Safari - the primary browser used by mo ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

What is the best way to swap the values of options between two input select elements?

I am trying to create a feature where I have two select dropdowns with the same options, and when a trigger is clicked, the option values are inverted between the two selects. Here is an example: <select id="source_currency"> <option value="BRL" ...

Frontend update: Changing the display format for dates

Received from the backend is an array of objects (leavedays)- var leavedays = [{"_id":"62d544ae9f22d","season":2022,"name":"LEAVEDAY1","dateFrom":"2022- 07-26T00:00:00.000Z","date ...

The Bootstrap navigation menu is functioning properly when opening, but has an issue when attempting

Creating a mirrored version of an HTML file using NuxtJS, I've included the following code snippet in the Navbar component for my NuxtJS project. <template> <section id="navigation-menu" class="menu menu3 cid-sLhoPz7Ycg" ...

A guide to sorting an object with integer keys by its values using JavaScript

I am facing an issue with sorting a map by values instead of keys. No matter what I do, it always ends up getting sorted by the keys. On the server side, I have a map that is already sorted. When I send this map to JavaScript using JSON, it gets re-ordere ...

Click on the React JS infinite render component to load more items

Just diving into the world of react/next and I'm a bit stuck on this issue. I've searched high and low, tried different solutions, but I can't seem to figure out what I'm missing or not grasping here. I understand that loadStats() is ...

What is the recommended way to configure the build.gradle file for the app build process?

I am currently working on building the app using the command provided below. /android gradlew assembleRelease My main query at this point is whether it is necessary to eliminate the debug of signingConfigs and debug of buildTypes when transitioning into r ...

Obtain the AJAX response in separate div elements depending on whether it is successful or an error

Currently, my jQuery script outputs the result in the same div for error or success messages: HTML <div id="error-message").html(res); JQUERY jQuery('#register-me').on('click',function(){ $("#myform").hide(); jQuery ...

Trigger the scrolling of one div when another div is scrolled

Link to Jsfiddle I'm attempting to activate my current scroll while I am outside that scroll, specifically in #DivDet Here is the code snippet of what I have tried so far: $("div#DivDet").scroll(function () { // Still trying to figure out what ...

What's the reason Rails is not recognizing relative JavaScript files?

app/assets/javascripts/application.js: //= require jquery //= require jquery_ujs //= require_tree . //= require bootstrap.min app/assets/javascripts/economy.js: $(document).ready(function() { console.log("loaded file"); }); app/views/economy/index.ht ...

Engage with React JS arrays of objects

I have a specific object structure that looks like the following: [ { "periodname": "Test", "periodtime": "" }, { "periodname": "", "periodtime&quo ...

Will the .replaceWith() method alter the code visible to search engines?

After successfully modifying the content of specific H1 elements to not return the value from a global variable using the following code; <script type="text/javascript"> $(document).ready(function() { $("H1").filter(function() { return $(this).text ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...