Get shadow root host element

Bart picture Bart · Aug 16, 2014 · Viewed 12.4k times · Source

When inserting a script into the shadow root of an element is there a way to refer to the host element?

var element = document.createElement('div');
var script = document.createElement('script');
script.innerHTML = 'console.log(host)'; // << How to get host element??

var shadow = element.createShadowRoot();
shadow.appendChild(script);

document.body.appendChild(element);

http://jsfiddle.net/9b1vyu4n/

Answer

darrylyeo picture darrylyeo · Dec 24, 2016

Node.getRootNode() was introduced in 2016.

You can now access the host element like so:

element.getRootNode().host