我有

和div一起的dom树:

<div id="root">
    1
    <div style="display: none;">
        2
    </div>
    3
</div>


我使用display: none遍历此dom树:

let element = document.getElementById('root');
let walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL);

while (walker.nextNode()) {
    let node = walker.currentNode;
    if (node.nodeType === 3) {
        console.log(node.nodeValue.trim());
    }
}


MDN documentation to TreeWalker method


  TreeWalker.nextNode()方法将当前Node按文档顺序移动到下一个可见节点。


因此,我认为TreeWalker.nextNode()应该跳过带有的div。但这不是:



let element = document.getElementById('root');
let walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL);

while (walker.nextNode()) {
    let node = walker.currentNode;
    if (node.nodeType === 3) {
        console.log(node.nodeValue.trim());
    }
}

<div id="root">
    1
    <div style="display: none;">
        this text node shouldn't be obtained with TreeWalker
    </div>
    3
</div>





那么,为什么不跳过呢?

最佳答案

因为在这种情况下可见项不属于


  在dom中可见


相反,它属于


戴上TreeWalker.whatToShow面罩,
TreeWalker.filter接受

10-01 01:20