Export (0) Print
Expand All

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.2Internet Explorer 9

Syntax

JavaScript

p = object.filter

Property values

Type: Object

A NodeFilter function that returns ones of the following values:

FILTER_ACCEPT (1)

Accept the node.

FILTER_REJECT (2)

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

FILTER_SKIP (3)

Skip the node. Child nodes are considered.

Standards information

Remarks

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
}

Examples

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>
<html>
<head>
<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 += node.id + "<br/>";
    }
    
    document.getElementById("results").innerHTML += results;
}
function refresh()                 
{
    window.location.reload( false );    // Reload our page.
}
</script>
</head>
<body>
    <!-- this is a comment node-->
    <table border="1" id="myTable">
      <tbody>
        <tr/>   
        <tr>
          <td><a href="" id="myLink">Text inside anchor</a></td>
        </tr>
      </tbody>
    </table>
    
    <div id="results">Results:<br/></div>
    
<button onclick="findNodes()">Find Nodes</button>
<button onclick="refresh()">Reload</button>
</body>
</html> 

See also

NodeIterator
TreeWalker

 

 

Show:
© 2015 Microsoft