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


I want to add an attribute for this selected element


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

1 Answer 1


In most cases, you can set the attribute directly.


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

    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 {
        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.

  • Thank you so much, This helped.
    – Naveen K N
    Jun 16, 2020 at 16:06
  • I am trying this with a lightning-button and the disabled attribute and it just isn't working. I've also tried the "disabled={disableButton}" approach (salesforce.stackexchange.com/questions/367162/…) which is similar to this but that only partially works as it sets the button to disabled but never removes the attribute when it's time for the button to no longer be disabled. Jul 14 at 14:26
  • 1
    FWIW the only way I could get this working was to use a custom HTML field "data-disabled={disabledButton}" and then using CSS to disable the button myself. Again the "disabled={disableButton}" just wasn't working for my lightning-button. Jul 14 at 16:22

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.