How to apply CSS in Lightning Web Component through Javascript

 parentComponent.html
<template>

    <h1>Brahmanaidu</h1>

    <p>Hi this is Brahmanaidu Mandalapu</p>

    <p>Hi welcome to Sfdcscenarios.blogspot.com</p>

    <lightning-button label="change styling"  class="btn" variant="success" onclick={handleChange}>

    </lightning-button>

</template>

parentComponent.js

import { LightningElement,api } from 'lwc';

	export default class ParentComponent extends LightningElement {

	renderedCallback(){

		this.template.querySelector("h1").style.color="blue";

		this.template.querySelector("h1").style.textAlign="center";

                this.template.querySelectorAll("p").forEach(item=>{

                Object.assign(item.style, {color:'blue',textAlign:'center',fontSize:'15px'});

    });

}

handleChange(){

	//innerHTML is used to modify the content 

	this.template.querySelector("h1").innerHTML="Mandalapu Brahmanaidu";

      this.template.querySelectorAll("p").forEach(item=>{
            Object.assign(item.style, {color:'red',textAlign:'center',fontSize:'25px'});

    });

}

}

LightningApplication

<aura:application extends="force:slds">

	<c:parentComponent>

	</c:parentComponent>

</aura:application>

Comments