Guide: How to Filter/Traverse DOM Tree using JavaScript

Did you know there is a JavaScript API whose sole mission is to provide filter out and repeat through the nodes we want from a DOMboom? In fact, there are not one, but there are two such APIs: NodeIterator and TreeWalker. They are quite similar, with some useful differences. Both can return a list of nodes that exist under a particular root node while satisfying any predefined and / or customized filter rules applied to them. The predefined filters available in the APIs can help us with that target different types of nodes such as text nodes or element nodes, and custom filters (added by us) can filter the forest further, for example by searching for nodes with specific content. The list of nodes returned is iterable, ie they can be looped through, and we can work with all individual nodes in the list.

How to use the NodeIterator API

A NodeIterator object can be created using the createNodeIterator () method of the document interface. This method has three argumentsThe first is required; it is the root node that contains all the nodes we want to filter. The second and third arguments are optionalThey are the predefined and custom filters, respectively. The predefined filters are available for use as constants of the NodeFilter object For example, if the constant NodeFilter.SHOW_TEXT is added as the second parameter, an iterator is returned for a list of all text nodes below the root nodeNodeFilter.SHOW_ELEMENT will return only the element nodesView a full list of all available constants The third argument (the custom filter) is one function that implements the filter Here’s one example code snippet <! doctype html>
txt
How are you?

Assuming we want to extract the contents of all text nodes located in the #wrapper div, this is how we go about it with NodeIterator: var div = document.querySelector (‘# wrapper’); var nodeIterator = document.createNodeIterator (div, NodeFilter.SHOW_TEXT); while (nodeIterator.nextNode ()) {console.log (nodeIterator.referenceNode.nodeValue.trim ());} / * console output[Log] this is the page wrapper[Log] Hey[Log][Log] How are you?[Log] The nextNode () method of the NodeIterator API returns the next node in the list of iterable text nodesIf we use it in a while loop to access every node in the list, we log the cropped content of each text node in the console. The referenceNode property of NodeIterator returns the node the iterator is currently attached to As you can see in the output, there are some text nodes with only empty spaces for their contents. We can avoid showing this empty content using a custom filter var div = document.querySelector (‘# wrapper’); var nodeIterator = document.createNodeIterator (div, NodeFilter.SHOW_TEXT, function (node) {return (node.nodeValue.trim ()! == “”)? NodeFilter.FILTER_ACCEPT: NodeFilter.FILTER_REJECT;}); while (nodeIterator.nextNode ()) {console.log (nodeIterator.referenceNode.nodeValue.trim ());} / * console output[Log] this is the page wrapper[Log] Hey[Log] How are you?*/ The custom filter function returns the constant NodeFilter.FILTER_ACCEPT if the text node is not empty, which leads to the inclusion of that node in the list of nodes the iterator will iterate over. In contrast, the constant NodeFilter.FILTER_REJECT is returned at exclude the empty text nodes from the iterable list of nodes.

How to use the TreeWalker API

As I said before are the NodeIterator and TreeWalker APIs similar to each other TreeWalker can be created using the createTreeWalker () method of the document interface. This method, like createNodeFilter (), has three arguments the root node, a predefined filter, and a custom filter If we use the TreeWalker API instead of NodeIterator the previous code snippet looks like this: var div = document.querySelector (‘# wrapper’); var treeWalker = document.createTreeWalker (div, NodeFilter.SHOW_TEXT, function (node) {return (node.nodeValue.trim ()! == “”)? NodeFilter.FILTER_ACCEPT: NodeFilter.FILTER_REJECT;}); while (treeWalker.nextNode ()) {console.log (treeWalker.currentNode.nodeValue.trim ());} / * output[Log] this is the page wrapper[Log] Hey[Log] How are you?*/ Instead of referenceNode, the TreeWalker API’s currentNode property is used to access the node that the iterator is currently attached toIn addition to the nextNode () method, Treewalker has other useful methods. The previousNode () method (also present in NodeIterator) returns the previous node of the node to which the iterator is currently anchored. Similar functionality is performed by the parentNode (), firstChild (), lastChild (), previousSibling (), and nextSibling () methods. These methods are only available in the TreeWalker API Here’s a code sample for that executes the last child of the node the iterator is anchored in: var div = document.querySelector (‘# wrapper’); var treeWalker = document.createTreeWalker (div, NodeFilter.SHOW_ELEMENT); console.log (treeWalker.lastChild ()); / * output[Log] How are you?

  • /

Which API to choose

Choose the NodeIterator API if you want just need a simple iterator to filter and loop through the selected nodes. And choose the TreeWalker API when you need must have access to the filtered nodes family, like their immediate brothers and sisters.

How to Filter/Traverse DOM Tree using JavaScript: benefits

Faq

Final note

I hope you like the guide How to Filter/Traverse DOM Tree using JavaScript. In case if you have any query regards this article you may ask us. Also, please share your love by sharing this article with your friends. For our visitors: If you have any queries regards the How to Filter/Traverse DOM Tree using JavaScript, then please ask us through the comment section below or directly contact us. Education: This guide or tutorial is just for educational purposes. Misinformation: If you want to correct any misinformation about the guide “How to Filter/Traverse DOM Tree using JavaScript”, then kindly contact us. Want to add an alternate method: If anyone wants to add more methods to the guide How to Filter/Traverse DOM Tree using JavaScript, then kindly contact us. Our Contact: Kindly use our contact page regards any help. You may also use our social and accounts by following us on Whatsapp, Facebook, and Twitter for your questions. We always love to help you. We answer your questions within 24-48 hours (Weekend off). Channel: If you want the latest software updates and discussion about any software in your pocket, then here is our Telegram channel.

How to Filter Traverse DOM Tree using JavaScript 2021  2022  - 52How to Filter Traverse DOM Tree using JavaScript 2021  2022  - 31How to Filter Traverse DOM Tree using JavaScript 2021  2022  - 19How to Filter Traverse DOM Tree using JavaScript 2021  2022  - 41