GetElementById from within Shadow DOM

Yuriy Kravets picture Yuriy Kravets · Mar 11, 2019 · Viewed 7.5k times · Source

I have a custom-element with shadow DOM, which listens to attribute target change.
target is supposed to be the ID of the element which my component is supposed to be attached to.

I've tried using querySelector and getElementById to get the element of the outer DOM, but it always returns null.

console.log(document.getElementById(target));
console.log(document.querySelector('#' + target));

Both of the above return null.

Is there a way to get a reference to the element in the parent document from within shadow DOM?

Answer

Penny Liu picture Penny Liu · May 7, 2019

You just have to call Shadow​Root.

this.shadowRoot.getElementById('target') should work.

Here's an example, the get syntax will bind an object property to a function.

get target() {
    return this.shadowRoot.getElementById('target');
}