1

I have two LWCs that I have put in a community page. I wanted to select an element of the other LWC from the other LWC, which I currently do not know how.

So, basically, my question is that, is there a way we can select an element in LWC1 from LWC2?

In native JavaScript, I believe this is how it's done:

document.querySelector('.some-classname');

But I've tried it in LWC and it didn't work.

3

By design, see e.g. Shadow DOM, that is not possible.

Edit your question to say exactly what you are aiming to do here between the two LWCs as how best to do that can depend on that.

Typically for LWCs that are not directly related, and assuming you have control over both LWCs, use the Lightning Message Service when the LWCs are running in the normal Salesforce desktop.

For Communities (AKA Digital Experiences), in the past you had to use a separate pub/sub library for this (works fine, just extra code to add), but LMS was in beta for Communities in May 2021, so may be GA by now or GA soon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.