2

I want to access current script or shadow root from inside of shadowDOM.

And, final purpose is getting div.target element in same shadowDOM.

I try using document.currentScript. However, it returns null. Therefore, I cannot detect where shadowDOM I am in.

Is there a way to do it?

<template id="template">
    <div class="target"></div>
    <script>
        // How to access self script element or above element which has target class?

        console.log(document.currentScript)
        // null
    </script>
</template>
<div class="sr"></div>

<script>
document.querySelector(".sr").attachShadow({mode: "open"}).append(
    document.querySelector("#template").content.cloneNode(true)
)
</script>
blz
  • 837
  • 7
  • 20

1 Answers1

1

You cannot do that because of a security or implementation limitation as pointed in this post.

To access the Shadow DOM you should use getRootNode() as described in this other post.

Supersharp
  • 29,002
  • 9
  • 92
  • 134