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 Traversing Ancestors - parents() Method Example</title> <style> body { font-family: Arial, sans-serif; padding: 40px; background-color: #f0f4f8; } h1 { color: #1a237e; } p { font-size: 15px; color: #37474f; margin-bottom: 30px; } .container { padding: 20px; border: 2px solid #3949ab; border-radius: 6px; background: #ffffff; position: relative; } .box { padding: 15px; margin: 15px; background: #e8eaf6; border-radius: 4px; position: relative; cursor: pointer; } .highlight { background-color: #c8e6c9 !important; /* light green */ } .info { margin-top: 20px; padding: 12px 16px; background: #ffffff; border: 1px solid #ccc; border-radius: 4px; color: #263238; font-size: 14px; display: inline-block; } </style> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> </head> <body> <h1>jQuery Traversing Ancestors - <code>parents()</code> Method</h1> <p>Click the innermost box. All ancestor elements up to <code><body></code> will be highlighted to demonstrate how <code>parents()</code> collects every ancestor.</p> <div class="container" id="outer"> <div class="box" id="middle"> <div class="box" id="inner">Click Me</div> </div> </div> <div class="info" id="infoBox">Click the innermost box above.</div> <script> $(function() { $('#inner').click(function() { // clear previous highlights $('.container, .box').removeClass('highlight'); // collect and highlight all ancestors var $ancestors = $(this).parents(); $ancestors.addClass('highlight'); // update info var names = $ancestors.map(function() { return this.tagName.toLowerCase() + (this.id ? '#' + this.id : ''); }).get().join(' → '); $('#infoBox').text('Ancestors: ' + names); }); }); </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