Document.createNodeIterator tutorial
last modified August 24, 2023
Document.createNodeIterator tutorial shows how to create a node interator
with Document.createNodeIterator method in JavaScript and
iterate over nodes in a document.
Document.createNodeIterator
Document.createNodeIterator() creates a NodeInterator.
NodeIterator is used to iterate over nodes in a document.
The function has the following synopsis:
let nodeIterator = document.createNodeIterator(root, whatToShow, filter);
The root is the node where the iterator is created. The whatToShow
is a bit mask such as NodeFilter.SHOW_COMMENT or
NodeFilter.SHOW_ELEMENT which determines what types of nodes should
be returned by the NodeIterator.
The filter is an optional parameter; it 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.
Document.createNodeIterator example
The following example demonstrates the usage of the document's
createNodeIterator function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document.createNodeIterator</title>
</head>
<body>
<h1>Iterating DOM in JavaScript</h1>
<p>
A paragraph.
</p>
<div>
A generic container with an
<em>inline</em> element.
</div>
<ul>
<li>powerful</li>
<li>solid</li>
<li>grounded</li>
</ul>
<script src="main.js">
</script>
</body>
</html>
In the example, we have iterate over the document body tag elements and print their names to the console.
window.onload = function () {
getChildren(document.body);
}
function getChildren(mytag) {
const nodeIter = document.createNodeIterator(
mytag,
NodeFilter.SHOW_ELEMENT,
(node) => {
return NodeFilter.FILTER_ACCEPT;
}
);
let cnode;
while (cnode = nodeIter.nextNode()) {
console.log(cnode.tagName.toLowerCase());
}
}
The JavaScript code creates a node iterator and iterates over elements of a body tag.
window.onload = function () {
getChildren(document.body);
}
When the document is fully loaded, we call the getChildren
function and pass it the document's body tag.
const nodeIter = document.createNodeIterator(
mytag,
NodeFilter.SHOW_ELEMENT,
(node) => {
return NodeFilter.FILTER_ACCEPT;
}
);
A node iterator is created with document.createNodeIterator.
With NodeFilter.SHOW_ELEMENT we tell the iterator to return
elements.
while (cnode = nodeIter.nextNode()) {
console.log(cnode.tagName.toLowerCase());
}
We iterate over the elements in the while loop using the iterator's
nextNode
method. We output the element tag names.
In this article we have iterated over elements of a body tag using a node iterator.