小编典典

如何使用JavaScript在用户代理影子根目录中获取元素?

javascript

我需要从Shadow DOM中获取元素并进行更改。我该怎么办?

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

阅读 354

收藏
2020-05-01

共1个答案

小编典典

这是一个例子:

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);

演示:

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>

我希望这能帮到您。

2020-05-01