0

Why in LWC this:

js

import { LightningElement, wire, api } from 'lwc';
export default class positionListLW extends LightningElement {

    connectedCallback() {
        const element = document.getElementById('t');
        console.log('element: ' + element);
        //elem.innerHTML = 'New text!';
    }
}

html

<template>
<div id="t">123</div>
</template>

Doesn't work:

enter image description here

Also i tryed "this.template.getElementById('t');" which returned an error "this.template.getElementById is not a function"

5
  • The reason is lwc framework changes the id you define in the html template to some unique values and that is where your defined id becomes irrelevant. As per the documentation you should not use ID selectors to find element in the DOM. Commented Jun 3, 2021 at 6:32
  • developer.salesforce.com/docs/component-library/documentation/… - 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. Commented Jun 3, 2021 at 6:33
  • Also, you should fetch the element in renderedCallback lifecycle hook, because DOM will be created after the connectedcallback execution and before the renderedcallback exectuion, hence this.template.querySelector([ID]) will return null in connectedcallback as the element has not been rendered in the DOM yet. (lwc.dev/guide/lifecycle) Commented Jun 3, 2021 at 6:39
  • @Ankur Gupta Thx! Commented Jun 3, 2021 at 6:52
  • 1
    @ankurgupta, turn the comments into an answer for upvoting.
    – Phil W
    Commented Jun 3, 2021 at 6:54

1 Answer 1

3

The reason is lwc framework changes the id you define in the html template to some unique values and that is where your defined id becomes irrelevant. As per the documentation you should not use ID selectors to find element in the DOM.

Document -

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.

Also, you should fetch the element in renderedCallback lifecycle hook, because DOM will be created after the connectedcallback execution and before the renderedcallback exectuion, hence this.template.querySelector([ID]) will return null in connectedcallback as the element has not been rendered in the DOM yet. (lwc.dev/guide/lifecycle)

Try to use this.template.querySelector('param') where param can be any name or class attribute as well as data-* attribute of any element.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .