Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get shadow root host element

Tags:

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/

like image 364
Bart Avatar asked Aug 16 '14 12:08

Bart


People also ask

What is a shadow root element?

The element that the tree is attached to ( <my-header> ) is called the shadow host. The host has a property called shadowRoot that refers to the shadow root. The shadow root has a host property that identifies its host element. The shadow tree is separate from the element's children .


2 Answers

Node.getRootNode() was introduced in 2016.

You can now access the host element like so:

element.getRootNode().host
like image 163
darrylyeo Avatar answered Oct 31 '22 12:10

darrylyeo


I got this finally figured out.

According to the specification (working draft) a ShadowRoot has a read only property called host. http://www.w3.org/TR/shadow-dom/#shadowroot-object

interface ShadowRoot : DocumentFragment {
    ...
    readonly    attribute Element        host;
    ...
};

You can get to the shadow root by walking up the DOM tree.

while(e.nodeType != 11) { // 11 = DOCUMENT_FRAGMENT_NODE
    e = e.parentNode;
}
var hostElement = e.host

In my case it was simpler since the shadow root was the parent node of the script itself.

document.currentScript.parentNode.host

http://jsfiddle.net/9b1vyu4n/2/

like image 37
Bart Avatar answered Oct 31 '22 12:10

Bart