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?
You just have to call ShadowRoot.
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');
}