Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <title>Recursive Traversal</title> <style> .comment { margin: 10px; padding: 10px; border: 1px solid #ccc; } .reply { margin-left: 20px; border-left: 2px solid #aaa; } </style> </head> <body> <div class="comments"> <div class="comment"> <p>Comment 1</p> <div class="reply"> <p>Reply 1-1</p> <div class="reply"> <p>Reply 1-1-1</p> </div> </div> <div class="reply"> <p>Reply 1-2</p> </div> </div> <div class="comment"> <p>Comment 2</p> <div class="reply"> <p>Reply 2-1</p> </div> </div> </div> <script> function traverseComments(node) { if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('comment')) { document.body.insertAdjacentHTML('beforeend', `<p>Comment: ${node.querySelector('p').textContent}</p>`); } if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('reply')) { document.body.insertAdjacentHTML('beforeend', `<p>Reply: ${node.querySelector('p').textContent}</p>`); } for (let i = 0; i < node.childNodes.length; i++) { traverseComments(node.childNodes[i]); } } traverseComments(document.querySelector('.comments')); </script> </body> </html>