HTML DOM createNodeIterator() Method
The createNodeIterator() Method is used to create a node iterator and hence using that node iterator we can iterate over nodes.
Syntax:
const nodeIterator = document.createNodeIterator(root[, whatToShow[, filter]]);
Parameters:
- root: The root node from which to begin the Node Iterator’s traversal.
- whatToShow(Optional): This is an optional argument representing a bitmask created by combining the constant properties of NodeFilter. The following are the possible values of unsigned constant.
Constant |
Return Value |
Constant Description |
NodeFilter.SHOW_ALL |
1
|
Shows all nodes. |
NodeFilter.SHOW_COMMENT |
128
|
Shows Comment nodes. |
NodeFilter.SHOW_DOCUMENT |
256
|
Shows Document nodes. |
NodeFilter.SHOW_DOCUMENT_FRAGMENT |
1024
|
Shows DocumentFragment nodes. |
NodeFilter.SHOW_DOCUMENT_TYPE |
512
|
Shows DocumentType nodes. |
NodeFilter.SHOW_ELEMENT |
1
|
Shows Element nodes. |
NodeFilter.SHOW_PROCESSING_INSTRUCTION |
64
|
Shows ProcessingInstruction nodes. |
NodeFilter.SHOW_TEXT |
4
|
Shows Text nodes. |
- filter(Optional): An object implementing the NodeFilter interface. Exp, NodeFilter.FILTER_ACCEPT.
Return Value: This method returns a node iterator.
Example: In this example, we will create a node iterator using this method and will iterate using the nextNode() method.
<!DOCTYPE HTML>
< html >
< head >
< meta charset = "UTF-8" >
< title >HTML | DOM createNodeIterator() Method
</ title >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< p >
HTML | DOM createNodeIterator() Method
</ p >
< button onclick = "Geeks()" >
Click Here
</ button >
< p id = "a" ></ p >
< script >
var a = document.getElementById("a");
function Geeks(){
const nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_ELEMENT
)
console.log(nodeIterator)
let nextNode=nodeIterator.nextNode();
nextNode=nodeIterator.nextNode();
a.innerHTML =
'Next Node content is : '+nextNode.textContent;
console.log(nextNode);
}
</ script >
</ body >
</ html >
|
Output:
Before Clicking Button:
After Clicking Button:
In the console: in Console, the node iterator and the next node can be seen.
Supported Browsers:
- Google Chrome
- Edge
- Firefox
- Safari
- Opera
- Internet Explorer
Last Updated :
23 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...