Yaroslav Polubedov Yaroslav Polubedov - 19 days ago 12
HTML Question

how get element from shadow root with JavaScript?

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

<div>
<input type="range" min="100 $" max="3000 $">
</div>

Answer

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.

Comments