递归地浏览Shadow和Light DOM [英] Walk through Shadow and Light DOM recursively

查看:105
本文介绍了递归地浏览Shadow和Light DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图递归地遍历阴影 DOM(无论在哪里,都寻找第一个输入)。这似乎不是一个艰巨的任务,所以我写了以下代码

I am trying to walk through the shadow and light DOM recursively (looking for the first input, wherever it may be). This didn't seem to be such a hard task, so I wrote the following code

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

由于我可以出于某种原因而陷入无限循环似乎并没有弄清楚(我猜这与以下事实有关:可以再次在影子DOM中找到轻型DOM中的元素,但是影子DOM中的元素不必在轻型DOM中,但不是每个元素具有阴影DOM ...因此我被困住了)。

which ends up in an infinite loop for reasons I can't seem to figure out (my guess it has to do with the fact that elements that are in the light DOM can again be found in the shadow DOM, but elements in the shadow DOM need not be in the light DOM, but not every element has a shadow DOM... so I am stuck).

推荐答案

解决方案是等待聚合物准备就绪:

The solution is to wait that polymer is ready:

document.addEventListener('polymer-ready', function() {
    recursiveWalk(document.body, function (node) {
        console.log(node.nodeName);
    });
})

并使用shadowDom属性:

and to use the shadowDom property:

if ('shadowRoot' in node &&  node.shadowRoot) {
    var done = recursiveWalk(node.shadowRoot, func);
    if (done) {
       return true;
    }
}

http://jsfiddle.net/za1gn0pe/7/

这篇关于递归地浏览Shadow和Light DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆