Do you know there’s a JavaScript API whose sole undertaking is to filter and iterate throughout the nodes we would like from a DOM tree? In truth, now not one however there are two such APIs: NodeIterator and TreeWalker. They’re rather very similar to one any other, with some helpful variations. Each can go back an inventory of nodes which might be provide below a given root node whilst complying with any predefined and/or customized clear out laws carried out to them.

The predefined filters to be had within the APIs can lend a hand us goal other forms of nodes akin to textual content nodes or component nodes, and customized filters (added by way of us) can additional clear out the bunch, for example by way of searching for nodes with explicit contents. The returned record of nodes are iterable, i.e. they are able to be looped thru, and we will be able to paintings with the entire particular person nodes within the record.

The way to use the NodeIterator API

A NodeIterator object can also be created the usage of the createNodeIterator() manner of the file interface. This technique takes 3 arguments. The primary one is needed; it”s the root node that holds the entire nodes we need to filter.

The second one and 3rd arguments are non-compulsory. They’re the predefined and customized filters, respectively. The predefined filters are to be had to be used as constants of the NodeFilter object.

As an example, if the NodeFilter.SHOW_TEXT consistent is added as the second one parameter it is going to go back an iterator for a record of the entire textual content nodes below the basis node. NodeFilter.SHOW_ELEMENT will go back simplest the component nodes. See a complete record of all the available constants.

The 3rd argument (the customized clear out) is a serve as that implements the clear out.

Here’s an instance code snippet:



  
    
    File
  
  
    

identify

that is the web page wrapper

Hi

How are you?

txt some link
copyrights

Assuming we need to extract the contents of the entire textual content nodes which might be within the #wrapper div, that is how we pass about it the usage of NodeIterator:

var div = file.querySelector('#wrapper');
var nodeIterator = file.createNodeIterator(
  div,
  NodeFilter.SHOW_TEXT
);
whilst(nodeIterator.nextNode()) {
  console.log(nodeIterator.referenceNode.nodeValue.trim());
}
/* console output
[Log] that is the web page wrapper
[Log] Hi
[Log]
[Log] How are you?
[Log]
*/

The nextNode() manner of the NodeIterator API returns the following node within the record of iterable textual content nodes. After we use it in a whilst loop to get right of entry to each and every node within the record, we log the trimmed contents of each and every textual content node into the console. The referenceNode belongings of NodeIterator returns the node the iterator is recently connected to.

As you’ll be able to see within the output, there are some textual content nodes with simply empty areas for his or her contents. We will be able to steer clear of appearing those empty contents the usage of a customized clear out:

var div = file.querySelector('#wrapper');
var nodeIterator = file.createNodeIterator(
  div,
  NodeFilter.SHOW_TEXT,
  serve as(node) {
    go back (node.nodeValue.trim() !== "") ?
    NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
  }
);
whilst(nodeIterator.nextNode()) {
  console.log(nodeIterator.referenceNode.nodeValue.trim());
}
/* console output
[Log] that is the web page wrapper
[Log] Hi
[Log] How are you?
*/

The customized clear out serve as returns the consistent NodeFilter.FILTER_ACCEPTif the textual content node isn’t empty, which results in the inclusion of that node within the record of nodes the iterator will likely be iterating over. Opposite, the NodeFilter.FILTER_REJECT consistent is returned as a way to exclude the empty textual content nodes from the iterable record of nodes.

The way to use the TreeWalker API

As I discussed earlier than, the NodeIterator and TreeWalker APIs are very similar to each and every different.

TreeWalker can also be created the usage of the createTreeWalker() manner of the file interface. This technique, similar to createNodeFilter(), takes 3 arguments: the basis node, a predefined clear out, and a customized clear out.

If we use the TreeWalker API as an alternative of NodeIterator the former code snippet looks as if the next:

var div = file.querySelector('#wrapper');
var treeWalker = file.createTreeWalker(
  div,
  NodeFilter.SHOW_TEXT,
  serve as(node) {
    go back (node.nodeValue.trim() !== "") ?
    NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
  }
);
whilst(treeWalker.nextNode()) {
  console.log(treeWalker.currentNode.nodeValue.trim());
}
/* output
[Log] that is the web page wrapper
[Log] Hi
[Log] How are you?
*/

As an alternative of referenceNode, the currentNode belongings of the TreeWalker API is used to get right of entry to the node to which the iterator is recently connected. Along with the nextNode() manner, Treewalker has different helpful strategies. The previousNode() manner (additionally present in NodeIterator) returns the former node of the node the iterator is recently anchored to.

Equivalent capability is carried out by way of the parentNode(), firstChild(), lastChild(), previousSibling(), and nextSibling() strategies. Those strategies are simplest to be had within the TreeWalker API.

Right here’s a code instance that outputs the final kid of the node the iterator is anchored to:

var div = file.querySelector('#wrapper');
  var treeWalker = file.createTreeWalker(
  div,
  NodeFilter.SHOW_ELEMENT
);
console.log(treeWalker.lastChild());
/*  output
[Log] 

How are you?

*/

Which API to select

Make a selection the NodeIterator API, whilst you want only a easy iterator to clear out and loop throughout the decided on nodes. And, select the TreeWalker API, whilst you wish to get right of entry to the filtered nodes’ circle of relatives, akin to their rapid siblings.

The publish How to Filter and Traverse DOM Tree with JavaScript gave the impression first on Hongkiat.

WordPress Website Development

[ continue ]