Skip to main content
New tool CRON Expression Builder — preview next run times before you schedule Apex. Open the builder →
Diagram of LWC lifecycle hooks explaining why LWC querySelector returns null before render
LWC

LWC querySelector Returns Null: Fixing Silent Failures

When an LWC querySelector returns null, nothing throws, and several other lifecycle and runtime mistakes fail just as quietly: toasts vanish in LWR sites and datatables go blank on mobile. This guide starts from each symptom and shows the cause and the code that fixes it.

The short answer

this.template.querySelector() returns null when it runs in the constructor or connectedCallback, because the template has not rendered yet. Move the query to renderedCallback() behind a run-once flag, and select by lwc:ref, class or data attribute instead of id, since LWC rewrites template ids at render time.

Key takeaways Move DOM queries out of the constructor and connectedCallback into renderedCallback, guarded by a run-once flag. Select elements with lwc:ref, classes or data attributes, and scope queries to this.template or this instead of document. Replace platformShowToastEvent with lightning/toast in any component that may run in an LWR or Experience Builder site. Read new record ids in onsuccess, and branch on formFactor to keep lightning-datatable out of the Salesforce mobile app. Clone large Apex or wire payloads once on arrival and index them with plain objects and arrays under Lightning Web Security.

Your component works on a Lightning record page in your desktop browser. Then someone opens it in an LWR site or the Salesforce mobile app, and a button does nothing, a toast never appears, or a table renders as an empty box. The console stays clean, because none of these failures throw. Salesforce's runtime behavior anti-patterns post closed its LWC series on this class of bug, and this guide works backwards from each symptom to its cause and fix.

querySelector returns null or the wrong element

The template has not rendered yet

The constructor runs before anything is rendered, so this.template.querySelector() returns null there. connectedCallback() fires when the component is inserted, but on first connection its children have not rendered either. Without a guard you get a TypeError. With optional chaining, which most of us type out of habit, the call does nothing at all, which is worse because nobody notices.

import { LightningElement } from 'lwc';

export default class ShipmentSearch extends LightningElement {
    hasRendered = false;

    connectedCallback() {
        // First connection: the template is not rendered, so this is null
        const box = this.template.querySelector('[data-field="tracking"]');
        box?.focus(); // silently does nothing
    }

    renderedCallback() {
        if (this.hasRendered) {
            return;
        }
        this.hasRendered = true;
        this.template.querySelector('[data-field="tracking"]').focus();
    }
}

renderedCallback() is the first hook where your template exists. It runs after every render, including rerenders triggered by state changes, and rendering flows child to parent, so a parent's hook runs after its children's. One-time work needs a flag like hasRendered.

Keep two rules in mind inside that hook. Do not assign public properties, template-bound fields or wire configuration properties there: each change marks the component dirty, queues a rerender as a microtask, and can loop forever. Programmatic event listeners do belong there, and the browser ignores a duplicate registration of the same handler on the same element, so rerenders will not stack them.

Check conditional rendering before blaming timing. An element inside an lwc:if branch that is currently false is not in the DOM, and no hook will find it.

An id selector never matches

LWC rewrites template id attributes into globally unique values at render time, so this.template.querySelector('#trackingInput') is unreliable even after render. Select by lwc:ref, a class or a data attribute. My default is lwc:ref for single elements and data attributes for anything repeated, because refs are not allowed inside loops.

<template>
    <lightning-input lwc:ref="trackingInput" label="Tracking number"></lightning-input>
    <ul>
        <template for:each={shipments} for:item="shipment">
            <li key={shipment.Id} class="shipment-row" data-shipment-id={shipment.Id}>
                {shipment.Carrier__c}
            </li>
        </template>
    </ul>
</template>
focusSearch() {
    this.refs.trackingInput.focus();
}

revealShipment(shipmentId) {
    const row = this.template.querySelector(
        `.shipment-row[data-shipment-id="${shipmentId}"]`
    );
    if (row) {
        row.scrollIntoView({ block: 'nearest' });
    }
}

A few lwc:ref rules decide whether it fits. this.refs is a plain read-only object, and assigning to it is a runtime error. A ref name that does not exist returns undefined. You can't put lwc:ref on a <template> tag, and the template compiler throws if you put it inside for:each or iterator. When two elements share a name, the last one wins. Avoid walking this.template.children as well; the engine guarantees nothing about its structure or order.

document.querySelector finds nothing

Under Lightning Web Security, document.querySelector() and document.getElementById() are scoped to your component's sandbox, so they never reach elements owned by other components. They can still appear to work in Jest. Scope queries to this.template in a shadow DOM component, or to this in a light DOM component. If you need something from a sibling, have that component expose an @api method or dispatch an event you listen for. A "jump to first error" helper built on document.querySelector('.slds-has-error') can pass its Jest tests and still do nothing for users under LWS.

@api values and setTimeout races

@api is undefined in the constructor

A parent sets public properties after your constructor runs, so reading an @api property there returns undefined. Defaulting your own class fields in the constructor is fine. For data that depends on the property, I prefer a wire adapter with a reactive parameter, because it re-runs whenever the parent changes the value.

import { LightningElement, api, wire } from 'lwc';
import getShipmentEvents from '@salesforce/apex/ShipmentController.getShipmentEvents';

export default class ShipmentTimeline extends LightningElement {
    @api shipmentId;
    pageSize;

    constructor() {
        super();
        this.pageSize = 25;           // own field: fine
        console.log(this.shipmentId); // undefined: parent has not set it yet
    }

    @wire(getShipmentEvents, { shipmentId: '$shipmentId', pageSize: '$pageSize' })
    events;
}

The trade-off is that @wire needs a cacheable=true Apex method. If the call has side effects or must skip the cache, call it imperatively from connectedCallback() and accept that it reads the value once. If the parent can change the property later, move the call into a setter on the property.

setTimeout that only works on your machine

Two versions of this show up in code review. The first waits a fixed delay for Apex data. On a quiet org the data arrives first; on a busy day it does not, and the follow-up logic runs on an empty array. The second uses setTimeout(..., 0) to wait for the DOM to update. LWC batches DOM updates asynchronously, so a zero delay often lands after the render in testing. Nothing in the engine promises that ordering, and under load it stops holding.

// Fragile: both delays are guesses
handleRefresh() {
    loadEvents({ shipmentId: this.shipmentId }).then((result) => {
        this.events = result;
        setTimeout(() => this.scrollToLatest(), 0);
    });
    setTimeout(() => this.computeTotals(), 500);
}

The fixed version scrolls a list that the template marks with a ref. The ref sits on the <ul>, outside the loop, so the compiler accepts it.

<template>
    <ul lwc:ref="eventList" class="event-list">
        <template for:each={events} for:item="evt">
            <li key={evt.Id}>{evt.Description__c}</li>
        </template>
    </ul>
</template>
pendingScroll = false;

async handleRefresh() {
    try {
        this.events = await loadEvents({ shipmentId: this.shipmentId });
        this.computeTotals();
        this.pendingScroll = true;
    } catch (error) {
        this.loadError = error;
    }
}

renderedCallback() {
    if (this.pendingScroll) {
        this.pendingScroll = false;
        const list = this.refs.eventList;
        if (list) {
            list.scrollTop = list.scrollHeight;
        }
    }
}

await hands you the data once it exists, and renderedCallback() hands you the DOM after the render that used it. The pendingScroll flag stays out of the template, so resetting it inside the hook does not queue another render.

Works in Lightning Experience, silent elsewhere

Toasts in LWR and Experience Cloud

lightning/platformShowToastEvent works in Salesforce Classic, Lightning Experience and the mobile app. In LWR sites and Experience Cloud it is a no-op that shows nothing and logs nothing. lightning/toast lists Lightning Experience, Experience Builder sites and the Salesforce mobile app as supported, so it is what I use in any component that might be dropped into a site.

lightning/platformShowToastEvent lightning/toast
Lightning Experience Works Works
Salesforce mobile app Works Works
Salesforce Classic Works Not listed
LWR and Experience Builder sites Silent no-op Works
How you call it this.dispatchEvent(new ShowToastEvent({...})) Toast.show({...}, this)
import { LightningElement, api } from 'lwc';
import Toast from 'lightning/toast';
import bookPickup from '@salesforce/apex/ShipmentController.bookPickup';

export default class PickupRequest extends LightningElement {
    @api shipmentId;

    async handleBook() {
        try {
            await bookPickup({ shipmentId: this.shipmentId });
            Toast.show({
                label: 'Pickup booked for tomorrow',
                message: 'The carrier will confirm a time window by email.',
                variant: 'success',
                mode: 'dismissible'
            }, this);
        } catch (error) {
            Toast.show({
                label: 'Pickup not booked. Try again or call the depot.',
                variant: 'error',
                mode: 'sticky'
            }, this);
        }
    }
}

On small screens lightning/toast hides the icon and the message, so anything the user must know goes in label, which is also the one required attribute. variant accepts info, success, warning or error, and mode accepts dismissible or sticky.

No record id in onsubmit

When lightning-record-form or lightning-record-edit-form creates a record, event.detail.id in the submit handler is undefined, because the record does not exist yet. Read the id in onsuccess, which fires after the save once the server has assigned it. onsubmit is still the right place to adjust field values before they go to the server.

<template>
    <lightning-record-edit-form
        lwc:ref="shipmentForm"
        object-api-name="Shipment__c"
        onsubmit={handleSubmit}
        onsuccess={handleSuccess}>
        <lightning-input-field field-name="Carrier__c"></lightning-input-field>
        <lightning-input-field field-name="Status__c"></lightning-input-field>
        <lightning-button type="submit" label="Create shipment"></lightning-button>
    </lightning-record-edit-form>
</template>
handleSubmit(event) {
    event.preventDefault();
    const fields = event.detail.fields;
    // event.detail.id is undefined here for a new record
    if (!fields.Status__c) {
        fields.Status__c = 'Booked';
    }
    this.refs.shipmentForm.submit(fields);
}

handleSuccess(event) {
    const shipmentId = event.detail.id; // assigned by the server
    this.dispatchEvent(new CustomEvent('shipmentcreated', { detail: { shipmentId } }));
}

Blank datatable in the mobile app

lightning-datatable is not supported in the Salesforce mobile app. It renders in a desktop browser and in a browser's responsive mode, which is why it survives testing until someone opens the native app. Branch on @salesforce/client/formFactor, which returns Large for desktop, Medium for tablet and Small for phone. When the two experiences differ substantially, return a different template from render() instead of piling lwc:if blocks into one file.

import { LightningElement } from 'lwc';
import FORM_FACTOR from '@salesforce/client/formFactor';
import tableTemplate from './shipmentListTable.html';
import cardTemplate from './shipmentListCards.html';

export default class ShipmentList extends LightningElement {
    render() {
        return FORM_FACTOR === 'Large' ? tableTemplate : cardTemplate;
    }
}

I give the datatable to Large only, so tablet users (Medium) also get the card list. Because the table renders in responsive mode, field users' reports of missing data can look like a sharing problem until someone opens the native app. Before you put any base component in a mobile-facing feature, check its mobile support in the Component Reference.

Slow lists under Lightning Web Security

Data from Apex and Lightning Data Service wire adapters originates outside your component's sandbox, so under LWS every property access crosses a proxy boundary. For a record with a handful of fields the cost is invisible. Across thousands of rows, read again and again while you sort, filter and render, it adds up.

Clone the payload once when it arrives and work on the local copy. Salesforce does not prescribe a cloning method. I use JSON.parse(JSON.stringify(data)) because Apex and LDS payloads are JSON-shaped already, so one pass through the proxy produces plain objects that the rest of the component can read freely.

import { LightningElement, wire } from 'lwc';
import getOpenShipments from '@salesforce/apex/ShipmentController.getOpenShipments';

export default class ShipmentBoard extends LightningElement {
    rows = [];
    rowsByCarrier = {};

    @wire(getOpenShipments)
    wiredShipments({ data, error }) {
        if (data) {
            // One pass through the proxy, then plain local objects
            const local = JSON.parse(JSON.stringify(data));
            const byCarrier = {};
            for (const row of local) {
                if (!byCarrier[row.Carrier__c]) {
                    byCarrier[row.Carrier__c] = [];
                }
                byCarrier[row.Carrier__c].push(row);
            }
            this.rows = local;
            this.rowsByCarrier = byCarrier;
        } else if (error) {
            this.rows = [];
        }
    }
}

Inside a namespace sandbox, Set, Map and typed arrays carry the same proxy overhead. For tens of thousands of items I index with plain objects and arrays, as above, and keep Set and Map for small collections or for cases where I need their semantics, such as non-string keys or insertion order.

If the component only shows counts, aggregate in Apex and send a few rows instead of thousands.

public with sharing class ShipmentController {
    @AuraEnabled(cacheable=true)
    public static List<AggregateResult> countOpenByCarrier() {
        return [
            SELECT Carrier__c carrier, COUNT(Id) total
            FROM Shipment__c
            WHERE Status__c != 'Delivered'
            WITH USER_MODE
            GROUP BY Carrier__c
        ];
    }
}

What to watch for

  • A query guarded with optional chaining may be skipping its work without telling you. During development, log the element before you add the ?..
  • Assigning tracked state in renderedCallback() can loop indefinitely. Use a flag the template does not read.
  • lwc:ref cannot sit inside for:each or iterator. Use data attributes for repeated rows.
  • A green Jest run tells you nothing about LWS scoping, LWR containers or the native mobile app. Test in every container you ship to.
  • Only lightning/modal and lightning/datatable officially support class extension. Extending any other base component depends on internals that can change in any release, so wrap it and delegate through @api properties and events.
  • Do not override internal SLDS classes such as .slds-button_brand inside base components. Use the public --slds-* styling hooks; the --lwc-* hooks are legacy.

Originally reported by developer.salesforce.com

Frequently asked questions

Why does this.template.querySelector return null in connectedCallback?

On first connection the component's children have not rendered yet, so the element does not exist. Query in renderedCallback() and use a boolean flag so one-time work runs only once.

Why does querySelector by id not work in LWC?

LWC rewrites template id attributes into globally unique values at render time, so '#myId' selectors are unreliable. Use lwc:ref, a class or a data attribute instead.

Why is my LWC toast not showing in an Experience Cloud site?

ShowToastEvent from lightning/platformShowToastEvent is a silent no-op in LWR and Experience Cloud sites. Use Toast.show() from lightning/toast, which supports Experience Builder sites.

Why is lightning-datatable blank in the Salesforce mobile app?

lightning-datatable is not supported in the native mobile app, even though it renders in a desktop browser's responsive mode. Check FORM_FACTOR from @salesforce/client/formFactor and render an alternate template for phones and tablets.

Why is my @api property undefined in the constructor?

The parent sets public properties after your constructor runs. Read the value in connectedCallback(), or pass it to a wire adapter as a reactive '$property' parameter so the call re-runs when the value changes.

Why is my LWC slow with Lightning Web Security enabled?

Under LWS, every property access on Apex or LDS data crosses a proxy boundary, and Set, Map and typed arrays carry the same overhead. Clone large payloads once on arrival, use plain objects and arrays for big collections, and aggregate in Apex when the component only needs totals.

Newsletter

One email every Tuesday

New guides, tool updates, and the release-note changes that break things.

No spam. Unsubscribe in one click.

Comments

Loading comments...

Leave a Comment