获取 javascript 中自定义元素的 ID

Get ID of custom element in javascript

我正在为 Google Earth 创建一个 tampermonkey 脚本,它会在您按下某个键时隐藏工具栏。应该隐藏的元素之一如下所示:

<earth-toolbar id="toolbar" role="toolbar">...</earth-toolbar>

我正在尝试使用此代码隐藏它:

document.getElementById('toolbar').style.display = 'none'

请注意,它在控制台中也不起作用。

但是,我得到了这个错误。

Uncaught TypeError: Cannot read property 'style' of null at HTMLDocument.eval

是否可以在不修改实际创建自定义元素的代码的情况下访问自定义元素?如果可以,它是什么?

#toolbar#shadow-root 中,因此您必须访问该父级的 .root 属性 才能找到其中的元素:

document.querySelector('earth-app').root.querySelector('#toolbar').style.display = 'none';

https://earth.google.com/web/