How can I tell if an element is in a shadow DOM? How can I tell if an element is in a shadow DOM? javascript javascript

How can I tell if an element is in a shadow DOM?


If you call a ShadowRoot's toString() method, it will return "[object ShadowRoot]". According to this fact, here's my approach:

function isInShadow(node) {    var parent = (node && node.parentNode);    while(parent) {        if(parent.toString() === "[object ShadowRoot]") {            return true;        }        parent = parent.parentNode;    }    return false;}

EDIT

Jeremy Banks suggests an approach in another style of looping. This approach is a little different from mine: it also checks the passed node itself, which I didn't do.

function isInShadow(node) {    for (; node; node = node.parentNode) {        if (node.toString() === "[object ShadowRoot]") {            return true;        }    }    return false;}