Add or Remove CSS Style classes in LWC

 We can do this following two ways, we will explain both the ways in example lightning component.

add-and-remove-css-lwc

Using classList method to toggle css classes: 

The classList property returns the array of the class names of a selected element. The classList property is read-only, however, you can modify it by using the add() and remove() methods. To know more about classList.

Using track variables in lwc to change css classes:

Using track variable to add and remove class names to this track variable to change class for HTML elements. 

addAndRemoveCSS.html

<template>
    <lightning-card title="Add and Remove CSS Classes" icon-name="utility:hide">
        <div class="slds-m-around_medium">
            <div class="slds-border_left" data-id="myDiv">This is a Sample text to Add and Remove style using classList</div></br>
            <lightning-button class="slds-p-around_medium" onclick={addBorderRight} label="Add Border Right"></lightning-button>
            <lightning-button onclick={removeBorderRight} label="Remove Border Right"></lightning-button>
        </br></br>
            <div class={addRemoveClass}>This is a Sample text to Add and Remove style using variable</div></br>
            <lightning-button class="slds-m-around_medium" onclick={addBorderTopAndBottom} label="Add Border Top And Bottom"></lightning-button>
            <lightning-button onclick={removeBorderTop} label="Remove Border Top"></lightning-button>
        </div>    
    </lightning-card>
</template>

addAndRemoveCSS.js

import { LightningElement } from 'lwc';

export default class AddAndRemoveCSS extends LightningElement {
    // using classList method
    addBorderRight(){
        // This will add new class to existing classes 
        this.template.querySelector('[data-id="myDiv"]').classList.add('slds-border_right');
        
        // also add like this to replace entire class and add your classes
        //this.template.querySelector('[data-id="myDiv"]').className='slds-border_right slds-border_left';
    }

    // Remove class using remove method
    removeBorderRight(){
        this.template.querySelector('[data-id="myDiv"]').classList.remove('slds-border_right');
    }
    
    // Using variables to assign classes and bing this variable in html elements
    addRemoveClass; // It's used to set class 
    addBorderTopAndBottom(){
        this.addRemoveClass = 'slds-border_top slds-border_bottom';
    } 

    removeBorderTop(){
        this.addRemoveClass = 'slds-border_bottom';
    } 
}

addAndRemoveCSS.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Also found above code in Tech Shorts Git repo

Labels:
LWC
Join the conversation