Changing the class of an element in Svelte: A step-by-step guide

I am working on a svelte application and I want to implement row highlighting when a user clicks on it. Here is an example code snippet that demonstrates this functionality:

<div id="A" class="car-even">A</div>
<div id="B" class="car-odd">B</div>


<style>
    .car-even  {
        color: #008800;
        cursor: pointer;
    }

    .car-odd  {
        color: red;
        cursor: pointer;
    }

    .car-selected  {
        color: blue;
        background-color: #ffffaa;
        cursor: pointer;
    }
</style>

<script>
    row = document.getElementById('A')
    row.className = 'car-selected '
</script>

However, I encountered an issue with updating the className correctly in svelte. Can you help me identify what is wrong?

App.svelte

<script>
    import Car from './cars.svelte'
    let car = ''
    $: console.log('Car', car)
</script>

<Car bind:selected_car={car}/>

Cars.svelte

<script>
    let cars = ['Audi', 'BMW', 'Hillman', 'Hyundai', 'Jaguar']
    export let selected_car = ''
    let car_class = ['car-even', 'car-odd']

    function carClicked(car) {
        selected_car = car
        let car_row = document.getElementById(car)
        car_row.className = 'car-selected'
    }
</script>

{#each cars as car, index (car)}
    <div id={car} class="{car_class[index % 2]}" on:click={() => carClicked(car)}>{car}</div>
{/each}

<style>
    .car-even  {
        color: #008800;
        cursor: pointer;    
    }

    .car-odd  {
        color: #000088;
        cursor: pointer;
    }

    .car-selected  {
        background-color: #ffffaa;
        cursor: pointer;
    }
</style>

Answer №1

It appears that the example provided may not be working properly, as the `.car-selected` CSS class is not being compiled since it is not being utilized anywhere that the compiler recognizes. Upon inspecting the HTML, you can see that the class is added upon clicking (which also overrides/removes the other class).

To resolve this issue using the Svelte approach, consider utilizing the class:directive. Add this directive to the div within the "each" loop like so:

class:car-selected={car === selected_car}

If desired, you can eliminate the need for `carClicked()` by following this REPL link.

{#each cars as car, index (car)}
<div id={car}
         class="{car_class[index % 2]}"
         class:car-selected={car === selected_car}
         on:click={() => selected_car = car}
    >
    {car}
</div>
{/each}

(Additionally, to minimize redundancy and leverage Svelte's scoped styling, consider adding the following)

    div {
        cursor: pointer;
        user-select: none;
    }

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

Is there a skilled coder available to troubleshoot this carousel's HTML code?

Hello, I am struggling with the code snippet below that uses Bootstrap to create a carousel. The next and previous buttons are not working properly. <div id="testimonial-carousel" class="carousel slide" data-ride="carousel&qu ...

Tips for creating a rounded bottom for your header

Is it possible to create a rounded header similar to this one? https://i.stack.imgur.com/aYQbA.png ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

Panel with Bootstrap Collapse feature causes a slight movement when padding is applied

After applying the collapse behavior to a panel element, I noticed that the animation stops abruptly at the padding of .panel-body, causing it to snap instantly to height. This issue can be observed in the basic example on codepen: http://codepen.io/FiveSi ...

Unusual SASS results observed while utilizing extends functionality

Having issues with my SASS files: _android.scss: $width: 111px; @import 'child'; .android .child { @extend %child; } _ios.scss: $width: 999px; @import 'child'; .ios .child { @extend %child; } _child.scss: %child { wi ...

TailwindCSS: Footer component overlaps central panel when scrolling on mobile devices

https://play.tailwindcss.com/notWWuhDpr?size=546x752 My project consists of three key components: The header A scrollable main panel The footer While it was relatively easy to implement this layout on the web using the code provided in the link above, I ...

Bootstrap dropdown malfunction

I am having trouble with my dropdown menu. The browser is cutting off the blue box in the dropdown area. I'm not sure if I need to add some CSS or make changes to the Bootstrap code to fix this issue. I haven't made any unusual modifications, jus ...

Using JQuery, eliminate the transition effect from a child CSS class

I am facing an issue with transitioning an ID that has a child class. My goal is to transition the ID only, without affecting the class within it. Despite going through CSS and jQuery documentation, I have been unable to achieve this. The transitions are c ...

A difference in the way content is displayed on Firefox compared to Chrome, Edge, and Safari

Recently, I encountered an issue with a tool I had developed for generating printable images for Cross-Stitch work. The tool was originally designed to work on Firefox but is now only functioning properly on that browser. The problem at hand is whether th ...

Offspring of the superior element resting above another element

I'm dealing with a unique situation involving the Z-INDEX property. Check out my HTML setup below. <div class="player"> <div class="player-line"> <div class="player-handle"></div> <!-- /.player-handle --> </d ...

Struggling with getting the navigation bar to show up in a row instead of stacking

Hey there, I need some help with the layout of my page. Here's the link to the page I'm currently working on: At the moment, the list is showing up vertically instead of horizontally. CSS: li { display:inline; list-style-type:none; ...

Looking for an API to retrieve random quotes and images from a website?

Greetings, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS along with the basics of JS. Level of Expertise: Beginner During my exploration, I stumbled upon this intriguing website - . It stands out a ...

Strategies for identifying specific children in my particular situation

Here's a snippet of my code: <ul id='nav'> <li><h1 id='unique' class='title'>Topic</h1></li> <li><h1 class='toptitle'>Department</h1></ ...

Using HTML video to fill entire div container

I'm currently facing an issue with using an HTML video as a fullscreen background replacement for an image. The problem is that the video overflows and covers the entire page instead of staying within the constraints of the header section. Here is th ...

Tips for adjusting the position of the second child in my navigation menu using CSS

Struggling with customizing my navigation menu in CSS, I'm seeking assistance. My goal is to have the second child element of the navigation menu on a new line instead of below the first child (refer to the image for clarification). An example of the ...

Align list items vertically, even when they have varying heights

I am currently working on creating rows of images, with 3 images in each row. The data being used is dynamic, however, I have provided some sample HTML and CSS below: ul { margin: 0; padding: 0; list-style: none; width: 900px; } li { margin: 0; padding: ...

Inconsistencies with Colorbox behavior in an external HTML document

Encountering a strange issue with colorbox while attempting to display a "div" element from another HTML file. The code functions perfectly, except for the final "div" in the external file. The structure of my external file is as follows; div1 img par ...

JQuery Menu with Broken UL Formatting on Windows versions of IE and Firefox

Hey there! I've been struggling with a menu design that works perfectly on Mac browsers but is completely broken on Windows. I've spent hours trying to fix it and would really appreciate if a kind programmer could take a look and help me out. The ...

Varied elevations dependent on specific screen dimensions

There seems to be a minor issue with the height of the portfolio container divs at specific window widths. The problematic widths range from 1025 to 1041 and from 768 to 784. To visualize this, try resizing your browser window to these dimensions on the fo ...

Embracing the balance of a gradient backdrop

I'm looking to create a gradient background for my page that transitions from light blue in the center to dark blue on the sides in a symmetrical way. I've tried using a linear gradient that goes from left to right, but it doesn't achieve th ...