使用 javascript 获取影子根内的 html 个元素

Get html elements inside shadow root using javascript

我有例子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

您可以使用 QuerySelector 获取 ShadowRoot 中的元素

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

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

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

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