Home > Mobile >  How to Bind an CSS attribute to a Table Cell with Svelte
How to Bind an CSS attribute to a Table Cell with Svelte

Time:09-23

I understand that with Svelte (or any other framework) it's not a good idea to access the DOM directly, eg. document.getElementById and then do something over it. I have a non-dynamic table that is already on a page as a Svelte component then I also have the following data: an array representing the table row's cells (let's say I have 5 cells per row) and also another array where each element has the index number where I must add a CSS attribute active='1' in the correspondent table cell.

ex.: arrIdxs = [1,3,4] and arrCells = [a,b,c,d,e]

<table>
<tr>
<td>a</td>
<td active="1">b</td>
<td>c</td>
<td active="1">d</td>
<td active="1">e</td>
</tr>
</table>

What is a good way to accomplish that?

CodePudding user response:

I'm not sure i understand the use case, but you would have to do something like this:

<script>
    const arrIdxs = [1, 3, 4];
    const arrCells = ['a', 'b', 'c', 'd', 'e'];
</script>

<table>
    <tr>
        {#each arrCells as cell, index}
            <td class:active={arrIdxs.includes(index)}>{cell}</td>
        {/each}
    </tr>
</table>

<style>
    .active {
        background-color: red;
    }
</style>
  • Related