Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
Svelte how to bind div inside each lop to obtain a reference using this

I need to get a reference to every div created inside a each loop in svelte, then I'll use the reference to toggle css class of a certain div when the user clicks on previous div.

    let contentOptions;
    
    function handleClick(event) {
    
        contentOptions.classList.toggle("close");
    
    }
    
    {#each items as item, i}
      
      <div class="titleOption" on:click={handleClick}>
        <img src="./assets/{item.icon}"/>
        <span>{item.label}</span>
      </div>
      
      <div class="content close" bind:this={contentOptions}>Content Option {i}</div>
       
    {/each}

Items array have three objects, and it always appears the last div with text "Content Option 2" despite clicking on another div.

is possible to bind each div separately?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can solve this by making contentOptions an array, bind with the index bind:this={contentOptions[i]} and use the index inside the function to target the right reference > REPL

<script>
    const items = [{label: 'item1'}, {label: 'item2'}]
    let contentOptions = [];

    function handleClick(index) {
        contentOptions[index].classList.toggle("close");
    }
</script>

{#each items as item, i}

<div class="titleOption" on:click={() => handleClick(i)}>
    <span>{item.label}</span>
</div>

<div class="content close" bind:this={contentOptions[i]}>Content Option {i}</div>

{/each}

<style>
    .close {
        background: red;
    }
</style>

This would be an alternative way without the need of the extra array and handling binding and index REPL

<script>
    const items = [{label: 'item1'}, {label: 'item2'}]

    function handleClick(event) {
        event.currentTarget.nextElementSibling.classList.toggle('close')
    }
</script>

{#each items as item, i}

<div class="titleOption" on:click={handleClick}>
    <span>{item.label}</span>
</div>

<div class="content close">Content Option {i}</div>

{/each}

<style>
    .close {
        background: red;
    }
</style>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!