Walk through Shadow and Light DOM recursively

2019-05-20 22:32发布

问题:

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/