Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <title>Node Types Interactive Example</title> <style> #info { border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; } #output { border: 1px solid #ccc; padding: 10px; } button { cursor: pointer; margin-bottom: 10px; } </style> </head> <body> <div id="info"> <!-- This is a comment node --> <p>Element node with a <span>child element node</span> and some text.</p> </div> <button onclick="displayNodeTypes()">Show Node Types</button> <div id="output">Node types will be displayed here.</div> <script> function displayNodeTypes() { const infoDiv = document.getElementById('info'); const outputDiv = document.getElementById('output'); outputDiv.innerHTML = ''; // Clear previous output const nodeTypes = []; // Iterate over all child nodes of the div infoDiv.childNodes.forEach(node => { let typeDescription = ''; switch(node.nodeType) { case Node.ELEMENT_NODE: typeDescription = 'Element node: ' + node.tagName; break; case Node.TEXT_NODE: // Trim text content and check if it's not empty let textContent = node.textContent.trim(); if (textContent) { typeDescription = 'Text node: "' + textContent + '"'; } break; case Node.COMMENT_NODE: typeDescription = 'Comment node: "' + node.textContent.trim() + '"'; break; } // Only add non-empty descriptions if (typeDescription) { nodeTypes.push(typeDescription); const p = document.createElement('p'); p.textContent = typeDescription; outputDiv.appendChild(p); } }); // If no nodes are visible or found if (nodeTypes.length === 0) { outputDiv.textContent = 'No visible nodes found.'; } } </script> </body> </html>