问题
I need get elements from Shadow DOM and change it. How i can do it?
<div>
<input type=\"range\" min=\"100 $\" max=\"3000 $\">
</div>
回答1:
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.
回答2:
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.
You can only access open custom Shadow DOM (the ones that you create yourself), with the { mode: 'open' }
option.
element.attachShadow( { mode: 'open' } )
Update
It's true for most UX standard HTML elements: <input>
, <video>
, <textarea>
, <select>
, <audio>
, etc.
来源:https://stackoverflow.com/questions/38701803/how-to-get-element-in-user-agent-shadow-root-with-javascript