TreeWalker显示不可见的节点

时间:2017-09-30 00:06:25

标签: javascript html css

我的div为dom树,display: none

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

我使用TreeWalker迭代这个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.nextNode() method

  

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

因此,我认为应display: none跳过TreeWalker的div。但它不是:

&#13;
&#13;
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());
    }
}
&#13;
<div id="root">
    1
    <div style="display: none;">
        this text node shouldn't be obtained with TreeWalker
    </div>
    3
</div>
&#13;
&#13;
&#13;

那么,为什么不跳过它?

1 个答案:

答案 0 :(得分:1)

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

  

在dom中可见

相反,它属于