top of page
Search

Get Values from Template to Javascript in Lightning Web Components

Updated: Oct 12, 2021

To access elements rendered by your component, use the Template property to call a query method

this.template.querySelector(); this.template.querySelectorAll();
  • The Order of the elements is not guaranteed

  • Elements not rendered to the DOM aren’t returned in the querySelector() result.

  • Don’t use ID selectors. The IDs that you define in HTML templates may be transformed into globally unique values when the template is rendered. If you use an ID selector in JavaScript, it won’t match the transformed ID.



<!-- example.html -->
<template>
    <div>First <slot name="t1">Procodingskills</slot></div>
    <div>Second <slot name="t2">Lakshmi Deepak</slot></div>
</template>

// example.js
import { LightningElement } from 'lwc';
 
export default class Example extends LightningElement {
    renderedCallback() {
    
        this.template.querySelector('div'); 
                    // <div>Procodingskills</div>
                    
        this.template.querySelector('span'); 
                    // null
                    
        this.template.querySelectorAll('div'); 
        // [<div>Procodingskills</div>, <div>Lakshmi Deepak</div>]
    }
}

Note: Don’t use the window or document global properties to query for DOM elements. Also, we don’t recommend using JavaScript to manipulate the DOM.


This following video will show you real usage of QuerySelector() in LWC



Its not just you get query based on the CSS Class , you can also query the element based on the Custom data attributes defined in HTML file

lets take a look at this example


 <lightning-input type="text" class="input-c" data-id="skill_input" value={_skillName} label="Change your Skill" onchange={handleInputChange}>
        </lightning-input>

In JS file you can query the input value based in data-id="skill_input" checkout the syntax how you can refer you custom property in JS querySelector

this.template.querySelector("lightning-input[data-id=skill_input]").value;

Watch the following video for more details








62 views0 comments

Comments


bottom of page