使用javascript获取shadow root内的html元素

And*_*ter 5 html javascript dom html-parsing

我有示例HTML代码:

<section class="search-module">
    #shadow-root (open)
        <div class="app">
            <div class="title">Product Title</div>
        </div>
</section>
Run Code Online (Sandbox Code Playgroud)

通过此代码,我可以访问shadow root元素父容器:

var searchModule = document.getElementsByClassName("search-module").item(0);
Run Code Online (Sandbox Code Playgroud)

但无法shadow root使用此命令获取容器内的元素:

searchModule.getElementsByClassName("title") // undefined
Run Code Online (Sandbox Code Playgroud)

小智 17

您必须shadow-root先导航到然后才能获取它:

const searchModule = document.querySelector('.search-module');
const searchModuleRoot = searchModule && searchModule.shadowRoot;

const title = searchModuleRoot.querySelector('.title');
Run Code Online (Sandbox Code Playgroud)