The NodeIterator.previousNode() method sets the NodeIterator to the previous node in the document and returns the previous node. This method returns null when there are no nodes left in the set.
Syntax:
node = nodeIterator.previousNode();
Parameters: This method takes no parameter.
Return Value: This method returns the previous node in the set.
Example: In this example, we will create a node iterator and hence will iterate backward using the previousNode() method.
<!DOCTYPE HTML> < html > < head > < meta charset = "UTF-8" > < title >HTML | DOM previousNode() Method</ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > neveropen </ h1 > < p > HTML | DOM previousNode() 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 ) let nextNode=nodeIterator.nextNode(); nextNode=nodeIterator.nextNode(); var prevNode=nodeIterator.previousNode(); a.innerHTML = 'Previous Node content is : '+prevNode.textContent; console.log(prevNode); } </ script > </ body > </ html > |
Output:
Before Clicking Button:
After Clicking Button:
In the console: in Console, the previous node can be seen.
Supported Browsers:
- Google Chrome
- Edge
- Firefox
- Safari
- Opera
- Internet Explorer