Sub topic 6
DOM access: what your component can reach
This chapter covers which parts of the page a Lightning web component can read and change under Lightning Web Security (LWS), and why. It assumes you can write a basic LWC (template, class, metadata file), that you know modern JavaScript, and that you know what the same-origin policy is. It also assumes you know that every component belongs to a namespace. The earlier chapters on namespace isolation and distortions explain the mechanism. Here we apply it to the DOM.
The short version
Your component can reach three things reliably:
- Elements in its own template, through
this.template. - Elements it projects into through slots or owns in light DOM, through
this. - Elements it creates itself and attaches in a supported way.
It should not rely on reaching elements owned by other components, other namespaces, or the surrounding page. Under LWS those lookups can return null, return partial results, or behave differently from a plain browser.
Why the DOM is the sensitive part
The DOM is shared by everything on a Lightning page. Your component, Salesforce's own components, and components from managed packages all render into one document. If any script could call document.querySelector and read or write any node, a component from one namespace could read data rendered by another. That includes form values and record details.
LWS closes this gap by running each namespace's code in its own JavaScript sandbox. It then distorts the DOM APIs inside that sandbox so a script can only see nodes that belong to its own namespace. The page still has a single DOM. The distorted APIs filter what each namespace is allowed to see.
Two layers that work together
DOM access in LWC depends on two separate mechanisms:
- Shadow DOM encapsulation. Each component's template renders into a shadow tree. Under LWC's default synthetic shadow, code outside the component cannot use
querySelectorto reach inside it. This is a feature of the component model and exists independently of LWS. - LWS sandboxing and distortion. LWS adds namespace-level rules on top of encapsulation. Even for APIs that are not covered by shadow boundaries, such as
documentandwindow, LWS limits what each namespace gets back.
A lookup works only if both layers allow it. When a query unexpectedly returns null, ask which layer blocked it.
Querying your own template
The supported way to reach elements your component renders is this.template. It is the root of your component's shadow tree.
import { LightningElement } from 'lwc';
export default class FocusInput extends LightningElement {
handleClick() {
// Query only inside this component's own template.
const input = this.template.querySelector('lightning-input');
if (input) {
input.focus();
}
}
}Three points about this code:
this.template.querySelectorsearches only the elements your template declares. It does not search the shadow trees of child components.- You can still call public methods and set public properties on a child element you found.
input.focus()works becausefocus()is a public method oflightning-input. You cannot reach inside the child to read its private markup. - The
if (input)guard matters. The template might not have rendered the element yet, or a conditional directive such aslwc:ifmay have removed it.
Prefer refs to selectors
In current API versions, you can mark an element with lwc:ref and read it from this.refs. This avoids brittle CSS selectors and does not depend on class names.
<template>
<lightning-input lwc:ref="nameInput" label="Name"></lightning-input>
<lightning-button label="Focus" onclick={handleClick}></lightning-button>
</template>import { LightningElement } from 'lwc';
export default class FocusWithRef extends LightningElement {
handleClick() {
// refs is populated after the first render.
this.refs.nameInput?.focus();
}
}this.refs is available once the component has rendered, so do not read it in the constructor or connectedCallback. A ref works only for elements in your own template.
Timing
The template does not exist as DOM until the component renders. Use renderedCallback for work that needs rendered elements. It runs after every render, so guard one-time setup with a flag, as the third-party library chapter shows.
Why `id` and `document.getElementById` fail
LWC rewrites id attribute values in templates to keep them unique across components. The rendered id is not the string you wrote. A call such as document.getElementById('myInput') therefore finds nothing, and under LWS the call is also subject to namespace filtering.
The fixes are:
- Use
this.template.querySelector('[data-id="myInput"]'), wheredata-idis a custom data attribute you chose. - Use
lwc:ref. - For accessibility links such as
aria-labelledbybetween elements in the same template, use the id references in the same template. LWC rewrites both sides consistently.
Cross-component id references, such as a label in one component pointing at an input in another, do not work. The shadow boundary stops them.
Reaching up and out: `document` and `window`
Code that walks out of the component is where LWS differences show up most.
| Access | What to expect under LWS |
|---|---|
| `this.template.querySelector(...)` | Works for elements in your template. |
| `this.querySelector(...)` | Works for elements your component owns in light DOM or receives through slots. |
| `document.querySelector(...)` | Distorted. It can return only elements your namespace owns, and often returns `null` for page elements. |
| `document.body` | Reachable, but nodes you append are subject to ownership rules. Treat the body as shared and unsafe to rely on. |
| `window` | Each namespace gets its own sandboxed window. Globals you set are not visible to other namespaces. |
| `parentElement`, `closest`, and tree walking past your host | Stops at the boundary of what your namespace may see. |
Do not treat this table as a guarantee for any specific property. LWS distortions are updated between Salesforce releases. Rather than depend on a surprising result, rewrite the code so it does not walk outside the component.
Replace global lookups with design
If you find yourself writing document.querySelector('.slds-modal'), the real problem is that two components need to coordinate. Use one of these instead:
- Give the target component a public
@apimethod or property. - Dispatch a custom event from the child and handle it in the parent.
- Pass the data through a shared JavaScript module, with some care about namespace boundaries. The cross-namespace chapter covers this.
Light DOM and slots
Slotted content belongs to the component that wrote it, not the component that hosts the slot. Suppose a parent passes <span> into your slot. The span belongs to the parent's template, so:
this.template.querySelector('span')in your component does not find it, because it is not in your template.this.querySelector('span')can find it, because slotted nodes appear as children of your host element.slot.assignedNodes()returns the nodes assigned to a slot. Use it when you need to know what was passed in.
import { LightningElement } from 'lwc';
export default class SlotInspector extends LightningElement {
slotCount = 0;
handleSlotChange(event) {
// event.target is the slot element in this component's template.
this.slotCount = event.target.assignedNodes().length;
}
}<template>
<slot onslotchange={handleSlotChange}></slot>
<p>Items slotted in: {slotCount}</p>
</template>Reading slotted nodes is fine for inspecting them. Mutating nodes that another component owns is risky, because the owner's framework may re-render and overwrite your changes.
Adding DOM by hand: `lwc:dom="manual"`
LWC owns the DOM it renders. If you insert nodes with innerHTML or appendChild into a template element without telling LWC, the engine will block the operation. The opt-in is the lwc:dom="manual" directive on the container.
<template>
<div class="host" lwc:dom="manual"></div>
</template>import { LightningElement } from 'lwc';
export default class ManualDom extends LightningElement {
rendered = false;
renderedCallback() {
if (this.rendered) {
return;
}
this.rendered = true;
const host = this.template.querySelector('.host');
const note = document.createElement('p');
note.textContent = 'Added without LWC knowing about it.';
host.appendChild(note);
}
}Points to remember:
- Use
textContent, notinnerHTML, for any text that includes data.innerHTMLwith untrusted input is a script-injection risk, and the CSP chapter explains what the platform does to limit the damage. - Nodes you attach are owned by your namespace. Other namespaces cannot reach them, and your own queries can.
- Because LWC does not track these nodes, you remove them yourself if the component needs to clean up.
lwc:dom="manual"is for third-party libraries that draw into an element, such as charts and maps. It is not a general way to build UI. Prefer template markup whenever you can.
Events, retargeting, and `event.target`
Events cross shadow boundaries. To keep encapsulation, the browser and LWC retarget event.target: a listener outside a component sees the host element as the target, not the inner element that fired it. Inside your own template, event.target is the real element.
A common bug is a parent that checks event.target.dataset.id and gets undefined because the target is the child's host, not the inner button. Fix this by putting the data- attribute on the child's host element, or by having the child dispatch a custom event with the data in detail.
Use event.currentTarget for the element your handler is attached to. It does not change as the event propagates.
Common errors
- A query returns
nullon a page element you can see. The element belongs to another component or namespace. Query within your template, or communicate through a public API. getElementByIdfinds nothing. LWC rewrote the id. Usedata-attributes orlwc:ref.- An
Invalid mutationor "not allowed to modify" error when settinginnerHTML. The container needslwc:dom="manual". - Code works in a sandbox org but fails in production, or the reverse. The two orgs may differ in whether LWS is enabled, or the page may contain components from different namespaces. Compare the settings first.
- A library that appends to
document.bodyshows nothing or throws. Give it a container inside your template that haslwc:dom="manual", and pass that element to the library.
Checklist
- Query inside
this.templateor uselwc:ref. - Wait for
renderedCallbackbefore touching rendered nodes. - Never rely on
documentlookups to find elements outside your component. - Use public properties, methods, and custom events to talk to other components.
- Use
lwc:dom="manual"for hand-built DOM, andtextContentfor data.
Exercise
A component renders <input id="email"> in its template. A developer writes document.getElementById('email').focus() in a click handler, and it throws Cannot read properties of null. Give two reasons it fails and a corrected version.
Show answer
First, LWC rewrites id values in templates, so no element with the id email exists in the rendered DOM. Second, under LWS and shadow DOM, document lookups cannot reach into a component's template, so the namespace and shadow boundaries filter the result. The corrected version queries the component's own template: this.template.querySelector('input')?.focus(). A more robust version marks the input with lwc:ref="email" and calls this.refs.email?.focus().
Exercise
A child component fires a click that bubbles to a parent. The parent handler reads event.target.dataset.id and gets undefined, although the clicked button has data-id="42" inside the child's template. Why, and what are two ways to fix it?
Show answer
Event retargeting makes event.target the child's host element when the event is seen outside the child's shadow tree, so the parent never sees the inner button. One fix is to place the data-id on the child's host element in the parent's template. The other is to have the child dispatch a custom event with detail: { id: 42 }, which the parent reads from event.detail.id.