Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetElementById from within Shadow DOM

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?

like image 665
Yuriy Kravets Avatar asked Mar 11 '19 12:03

Yuriy Kravets


1 Answers

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');
}
like image 84
Penny Liu Avatar answered Nov 10 '22 16:11

Penny Liu