如何使用 JavaScript 获取用户代理影子根中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38701803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get element in user-agent shadow root with JavaScript?
提问by Yaroslav Polubedov
I need get elements from Shadow DOM and change it. How i can do it?
我需要从 Shadow DOM 获取元素并更改它。我该怎么做?
<div>
<input type="range" min="100 $" max="3000 $">
</div>
采纳答案by Ismail RBOUH
Here is an example:
下面是一个例子:
var container = document.querySelector('#example');
//Create shadow root !
var root = container.createShadowRoot();
root.innerHTML = '<div>Root<div class="test">Element in shadow</div></div>';
//Access the element inside the shadow !
//"container.shadowRoot" represents the youngest shadow root that is hosted on the element !
console.log(container.shadowRoot.querySelector(".test").innerHTML);
Demo:
演示:
var container = document.querySelector('#example');
//Create shadow root !
var root = container.createShadowRoot();
root.innerHTML = '<div>Root<div class="test">Element in shadow</div></div>';
//Access the element inside the shadow !
console.log(container.shadowRoot.querySelector(".test").innerHTML);
<div id="example">Element</div>
I hope this will help you.
我希望这能帮到您。
回答by Supersharp
You cannot access a Shadow DOM created by the browser to display a control, that is called a #shadow-root (user-agent)
in the Dev Tools. <input>
is one example.
您无法访问浏览器创建的 Shadow DOM 来显示控件,#shadow-root (user-agent)
在开发工具中称为 a 。<input>
就是一个例子。
You can only access opencustom Shadow DOM (the ones that you create yourself), with the { mode: 'open' }
option.
您只能使用该选项访问打开的自定义 Shadow DOM(您自己创建的 Shadow DOM){ mode: 'open' }
。
element.attachShadow( { mode: 'open' } )
Update
更新
It's true for most UX standard HTML elements: <input>
, <video>
, <textarea>
, <select>
, <audio>
, etc.
它是最UX标准的HTML元素真:<input>
,<video>
,<textarea>
,<select>
,<audio>
,等。