使用JavaScript获取影子根内的HTML元素

5

我有一个示例HTML代码:

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

使用这段代码,我可以访问影子根元素的父容器:

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

但是使用此命令无法获取影子根(shadow root)容器内的元素:

searchModule.getElementsByClassName("title") // undefined

这行代码:searchModule.getElementsByClassName("title") 运行得非常完美。在 JSBin 上进行了检查。 - vrintle
请考虑其他方法,例如在此处:https://help.apify.com/en/articles/2619262-how-to-scrape-pages-with-shadow-dom(我没有测试过..) - JB-007
我收到了“Uncaught TypeError: document.querySelector(...).item不是函数”的错误。 - johannes
2个回答

17

您需要先导航到shadow-root,然后才能获取它:

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

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

对于我的情况不起作用 - undefined

0

你可以使用QuerySelector来获取ShadowRoot内部的元素。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接