Walk through Shadow and Light DOM recursively

。_饼干妹妹 提交于 2019-11-26 21:57:00

问题


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

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


回答1:


The solution is to wait that polymer is ready:

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

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/



来源:https://stackoverflow.com/questions/33780562/walk-through-shadow-and-light-dom-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!