Windows Dev Center

filter property

Gets the function object that the iterator uses to filter nodes that go into TreeWalker hierarchies or NodeIterator lists.

Document Object Model (DOM) Level 2 Traversal and Range Specification, Section 1.2




p = object.filter


Property values

Type: Object

A NodeFilter function that returns ones of the following values:


Accept the node.


Reject the node. For TreeWalker, child nodes are also rejected. For NodeIterator, this flag is synonymous with FILTER_SKIP.


Skip the node. Child nodes are considered.

Standards information


The NodeFilter is a callback function that provides customized filtering for NodeIterator and TreeWalker. The filter function accepts a node as its only parameter, and indicates whether the node is accepted, rejected, or skipped.

function myFilter(node) {
    // NodeFilter function that returns one of the following flags:
    // NodeFilter.FILTER_ACCEPT, NodeFilter.FILTER_REJECT, NodeFilter.FILTER_SKIP


The following example searches for table and anchor tags and reports the value of the id attribute. Although the TreeWalker preserves the hierarchical relationship of nodes, you don't need to write recursive functions to walk the nodes in a hierarchy. The NodeFilter function skips nodes rather than rejecting them, which allows the function to examine all child nodes in the hierarchy.

Note  Appending content to the document while the TreeWalker is searching for nodes can cause and endless loop. To prevent this, the example collects all possible output in a temporary variable and appends it to the document after the TreeWalker is finished.

<!DOCTYPE html>
<script type="text/javascript">
// This is the NodeFilter function. It receives a node, and must return a NodeFilter flag.
function filter(node)
    if (node.tagName == "TABLE" || node.tagName == "A")
        return NodeFilter.FILTER_ACCEPT;
    return NodeFilter.FILTER_SKIP;
function findNodes()
    var tw = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, filter, false);
    var node, results = '';
    while (node = tw.nextNode()) {
        results += + "<br/>";
    document.getElementById("results").innerHTML += results;
function refresh()                 
    window.location.reload( false );    // Reload our page.
    <!-- this is a comment node-->
    <table border="1" id="myTable">
          <td><a href="" id="myLink">Text inside anchor</a></td>
    <div id="results">Results:<br/></div>
<button onclick="findNodes()">Find Nodes</button>
<button onclick="refresh()">Reload</button>

See also




© 2015 Microsoft