How to get element in shadow root using JavaScript?

I need to get the elements from the Shadow DOM and change it. How can i do this?

<div> <input type="range" min="100 $" max="3000 $"> </div> 
+7
source share
2 answers

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> 

Hope this helps you.

+10
source

You cannot access the Shadow DOM created by the browser to display a control called #shadow-root (user-agent) in Dev Tools. <input> is one example.

You can access only the open custom Shadow DOM (those that you create yourself), with the option { mode: 'open' } .

 element.attachShadow( { mode: 'open' } ) 

Refresh

This is true for most standard UX HTML elements: <input> , <video> , <textarea> , <select> , <audio> , etc.

+15
source

All Articles