2

is it possible to get and set the attribute values in the salesforce lightning web component

as you know we can select the element by using this syntax

this.template.querySelector('.s1')

I want to add an attribute for this selected element

this.template.querySelector('.s1').setAttr('checked');

it is not working currently, could you please share if there is any workaround for this.

4

In most cases, you can set the attribute directly.

Example:

<template>
    <lightning-input type="checkbox" label="Demo" name="demo">
    </lightning-input>
    <lightning-button onclick={toggle} label="Toggle">
    </lightning-button>
</template>

import { LightningElement } from 'lwc';

export default class App extends LightningElement {
    toggle() {
        let el = this.template.querySelector('lightning-input');
        el.checked = !el.checked;
    }
}

Use setAttribute if you're exposing a property that should appear in the DOM.

// myComponent.js
import { LightningElement, api } from 'lwc';

export default class MyComponent extends LightningElement {
    privateTitle;

    @api
    get title() {
        return this.privateTitle;
    }

    set title(value) {
        this.privateTitle = value.toUpperCase();
        this.setAttribute('title', this.privateTitle);
    }
}

This example causes the default "title" behavior to occur (display on mouse hover).

There's no need for setAttr, simply setting the properly directly works in most cases.

1
  • Thank you so much, This helped.
    – Naveen K N
    Jun 16 '20 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.