TransWikia.com

How do I get the Html Element (or Locker API SecureElement) for a child LWC component?

Salesforce Asked by Jason Clark on January 4, 2022

In an LWC component, this.template.querySelector() appears to return an Element (or probably SecureElement) for standard HTML elements, but something else for child components. For example:

this.template.querySelector('div').scrollIntoView();

This will find the first div and correctly scroll it into view. On the other hand:

this.template.querySelector('c-child').scrollIntoView();

does not work. I can verify that this.template.querySelector('c-child') is indeed returning an object that represents the first c-child custom LWC component, and the call to scrollIntoView() does not return an error, but the display does not move. I assume that the object return is not the SecureElement representing the <c-child> node in my <template>.

I am able to get the desired behavior by adding a public api method to c-child:

@api
scrollToHere() {
    this.template.querySelector('div').scrollIntoView();
}

and calling it from the parent, e.g.,

this.template.querySelector('c-child').scrollToHere();

But this seems unnecessary since there should be a element in the DOM to represent the <c-child> element, but either .querySelector('c-child') doesn’t return that element, or LWC elements don’t support standard SecureElement methods such as .scrollIntoView(). I tried a few variations such as this.template.querySelector('c-child').element.scrollIntoView(); without success.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP