我正在尝试递归地遍历阴影 和 光照 DOM(寻找第一个 input
,无论它在哪里)。这似乎不是什么难事,所以我写了下面的代码
recursiveWalk: function(node, func) {
var done = func(node);
if(done){
return true;
}
if('root' in node){
this.recursiveWalk(node.root, func);
if(done){
return true;
}
}
node = node.firstChild;
while (node) {
var done = this.recursiveWalk(node, func);
if(done){
return true;
}
node = node.nextSibling;
}
}
由于我似乎无法弄清楚的原因,它最终陷入无限循环(我猜这与以下事实有关:在 light DOM 中的元素可以再次在 shadow DOM 中找到,但是元素在shadow DOM 不需要在 light DOM 中,但不是每个元素都有 shadow DOM ......所以我被卡住了)。
最佳答案
解决方案是等待聚合物准备就绪:
document.addEventListener('polymer-ready', function() {
recursiveWalk(document.body, function (node) {
console.log(node.nodeName);
});
})
并使用 shadowDom 属性:
if ('shadowRoot' in node && node.shadowRoot) {
var done = recursiveWalk(node.shadowRoot, func);
if (done) {
return true;
}
}
关于javascript - 递归遍历 Shadow 和 Light DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780562/