首页 > 解决方案 > 使用javascript在shadow root中获取html元素

问题描述

我有示例HTML代码:

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

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

var searchModule = document.getElementsByClassName("search-module").item(0);

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

searchModule.getElementsByClassName("title") // undefined

标签: javascripthtmldomhtml-parsing

解决方案


你必须先导航到shadow-root然后你才能得到它:

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

const title = searchModuleRoot.querySelector('.title');

推荐阅读