Access Elements the Component Owns

To access elements rendered by a component with standard DOM APIs, use querySelector() with this.template or this. To locate elements in the DOM without a selector, use refs.

Don’t use the window or document global properties to query for DOM elements. See DOM Access Containment. Also, we don’t recommend using JavaScript to manipulate the DOM unless you’re working with a third-party library via lightning/platformResourceLoader. It’s better to use the Lightning Web Components HTML directives to write declarative code.

Important

querySelector() 

The standard way to access elements in the DOM is to use querySelector(). To locate shadow DOM nodes, use querySelector() or querySelectorAll() on this.template. For light DOM nodes, use one of those methods on this.

1// shadow DOM
2this.template.querySelector("div");
3
4// light DOM
5this.querySelector("div");

You can also use {element}.template.querySelector.

Note

Use these methods to look for the elements that your component rendered.

  • The order of elements is not guaranteed.
  • Elements not rendered to the DOM aren’t returned in the querySelector result.
  • Don’t use ID selectors with querySelector. 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.
  • For light DOM components, this.querySelector() searches through elements outside of the immediate template, such as light DOM children. Use a more specific selector to narrow the scope of the method.
  • If the component runs in an org with Lightning Locker enabled, be aware of a potential memory leak. If possible, the org should enable Lightning Web Security (LWS). Alternatively, consider using refs instead of querySelector.
  • Place light DOM components within a shadow DOM component. Lightning Locker and LWS don’t support light DOM components outside shadow DOM.
1<!-- example.html -->
2<template>
3  <div>First <slot name="task1">Task 1</slot></div>
4  <div>Second <slot name="task2">Task 2</slot></div>
5</template>
1// example.js
2import { LightningElement } from "lwc";
3
4export default class Example extends LightningElement {
5  renderedCallback() {
6    this.template.querySelector("div"); // <div>First</div>
7    this.template.querySelector("span"); // null
8    this.template.querySelectorAll("div"); // [<div>First</div>, <div>Second</div>]
9  }
10}

The lwc-recipes repo has a miscDomQuery component that demonstrates DOM querying using querySelectorAll.

Tip

Refs 

Refs locate DOM elements without a selector and only query elements contained in a specified template. First, add the lwc:ref directive to your element and assign it a value. To call that reference, use this.refs. In this example, the <div> element has the directive lwc:ref="myDiv", which this.refs references to access the <div> at runtime.

1<template>
2  <div lwc:ref="myDiv"></div>
3</template>
1export default class extends LightningElement {
2  renderedCallback() {
3    console.log(this.refs.myDiv);
4  }
5}

Considerations 

You must define the directive lwc:ref before calling this.refs. If you call this.refs for a nonexistent ref, it returns undefined. If the template contains duplicate lwc:ref directives, this.refs references the last <div>.

1<template>
2  <div lwc:ref="myDiv"></div>
3  <div lwc:ref="myDiv"></div>
4</template>

this.refs is a plain, read-only object. Trying to add, modify, or delete properties from within its component causes a runtime error. Its key is a string, and its value is a DOM element. The syntax for this.refs is the same for referencing elements in light DOM and shadow DOM.

Refs are configurable and writable, so refs defined in a component overwrite those from LightningElement.prototype.

You can’t apply lwc:ref to <template> elements, or to <slot> elements in light DOM.

1<template lwc:render-mode="light">
2  <template lwc:if={myTemplate} lwc:ref="myTemplate"></template>
3  <!-- Not allowed -->
4</template>
1<template lwc:render-mode="light">
2  <slot lwc:ref="mySlot"></slot>
3  <!-- Not allowed -->
4</template>

If you place lwc:ref in a for:each or iterator:* loop, the template compiler throws an error.

1<template for:each={items} for:item="item">
2  <div key={item} lwc:ref="foo"></div>
3  <!-- Not allowed -->
4</template>

Multiple Templates 

this.refs refers to the most recently rendered template in a multi-template component. When the template changes, the this.refs object will change too.

1import a from "./a.html";
2import b from "./b.html";
3
4export default class extends LightningElement {
5  count = 0;
6
7  render() {
8    return this.count % 2 === 0 ? a : b;
9  }
10
11  renderedCallback() {
12    console.log(this.refs);
13  }
14
15  increment() {
16    this.count++;
17  }
18}
19
20const cmp = createElement("c-component", { is: Component });
21// Logs `this.refs` for a.html
22
23cmp.increment();
24// Logs `this.refs` for b.html
25
26cmp.increment();
27// Logs `this.refs` for a.html

To conditionally define an element based on <template lwc:if={boolean}>, create multiple child templates under one parent template. In this example, this.refs.toggleDarkMode refers to the element inside of whichever child template is rendered.

1<template>
2  <template lwc:if={darkMode}>
3    <button lwc:ref="toggleDarkMode">Enable Light Mode</button>
4  </template>
5  <template lwc:else>
6    <button lwc:ref="toggleDarkMode">Enable Dark Mode</button>
7  </template>
8</template>

Access the Parent Element 

AVAILABLE API VERSIONS
Available in LWC API v62.0 and later

To access the HTMLElement of a Lightning web component from within a callback function, use this.hostElement in your component. The hostElement property lets you retrieve a property on the HTMLElement class. You can apply it to shadow DOM or light DOM components.

This example returns this.hostElement in a light DOM component.

1// c-light
2import { LightningElement } from "lwc";
3
4export default class extends LightningElement {
5  static renderMode = "light"; // default is 'shadow'
6
7  renderedCallback() {
8    console.log(this.hostElement); // logs <c-light>
9  }
10}

In light DOM, this.template.host returns undefined. In shadow DOM, this.hostElement is interchangeable with this.template.host.

See Also

Release Preview

This release is in preview. Features described here don't become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can't guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.