Codelab Editor
Free Online HTML Editor
Run
Learn jQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>jQuery contents() – Show All Child Nodes</title> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <style> body { font-family: Arial, sans-serif; background-color: #f4f7fa; padding: 30px; } h2 { color: #2c3e50; } .description { color: #555; margin-bottom: 20px; } .container { border: 2px solid #16a085; padding: 20px; background-color: #e8f8f5; width: 400px; cursor: pointer; position: relative; } .box { margin: 8px 0; padding: 10px; background-color: #d1f2eb; border: 1px solid #1abc9c; } .highlight { background-color: #ffd54f !important; outline: 2px solid #fbc02d; } .info-box { margin-top: 20px; padding: 10px 15px; background-color: #fff; border-left: 4px solid #3498db; box-shadow: 0 0 5px rgba(0,0,0,0.1); } .node-label { margin-bottom: 6px; font-size: 14px; color: #444; } .node-label span { font-weight: bold; color: #2c3e50; } </style> </head> <body> <h2>jQuery contents() – Show All Child Nodes</h2> <p class="description"> Click the box below to highlight all <strong>element nodes</strong> inside, and list the <strong>text and comment nodes</strong> separately below. </p> <div class="container" id="contentBox"> Some text node here. <div class="box">Div 1</div> <!-- This is a comment node --> <div class="box">Div 2</div> </div> <div class="info-box" id="nodeInfo"> <!-- Node info will appear here --> </div> <script> $(function () { $('#contentBox').on('click', function () { const $container = $(this); const $info = $('#nodeInfo'); // Reset previous highlights and output $container.find('.highlight').removeClass('highlight'); $info.empty(); $container.contents().each(function () { if (this.nodeType === 1) { // Element node (e.g., div) $(this).addClass('highlight'); } else if (this.nodeType === 8) { // Comment node const commentText = this.nodeValue.trim(); $info.append(`<div class="node-label"><span>Comment Node:</span> ${commentText}</div>`); } else if (this.nodeType === 3 && $.trim(this.nodeValue)) { // Text node (non-empty) const textPreview = this.nodeValue.trim().substring(0, 50); $info.append(`<div class="node-label"><span>Text Node:</span> "${textPreview}"</div>`); } }); }); }); </script> </body> </html>
Editor Commands
Ctrl
F
Find
Ctrl
G
Find Next
Ctrl
⇧
G
Find Previous
Ctrl
⇧
F
Find & Replace
Ctrl
]
Indent Code Right
Ctrl
[
Indent Code Left
⇧
Tab
Auto Indent Code
Ctrl
/
Line Comment
Ctrl
Alt
/
Block Comment
TutsInsider Actions
Alt
S
Run Code
Ctrl
C
Copy Editor Code
Ctrl
A
Select All Editor Code
Ctrl
S
Save/Download
Ctrl
Alt
X
Rotate
Ctrl
Alt
T
Switch Theme
Ctrl
⇧
C
Open Console
Esc
Close Console