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(selector) 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; } .outer { padding: 20px; border: 2px solid #3949ab; border-radius: 6px; background: #ffffff; } .wrapper { margin: 15px; padding: 15px; border: 2px dashed #1e88e5; border-radius: 4px; background: #e3f2fd; position: relative; } .inner-box { margin: 15px; padding: 15px; background: #e8eaf6; border-radius: 4px; cursor: pointer; } .highlight { background-color: #ff0 !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('.wrapper')</code> Method</h1> <p>Click the innermost box. Only the ancestor elements matching the selector <code>.wrapper</code> will be highlighted, demonstrating how the optional selector filters the set.</p> <div class="outer"> <div class="wrapper" id="level1"> <div class="wrapper" id="level2"> <div class="inner-box" id="inner">Click Me</div> </div> </div> <div class="wrapper" id="sibling">Sibling Target (not ancestor)</div> </div> <div class="info" id="infoBox">Click the inner box above.</div> <script> $(function() { $('#inner').click(function() { // clear previous highlights $('.wrapper').removeClass('highlight'); // collect only ancestors matching '.wrapper' var $matches = $(this).parents('.wrapper'); $matches.addClass('highlight'); // list matched ancestor IDs var ids = $matches.map(function() { return '#' + this.id; }).get().join(' → '); $('#infoBox').text( ids ? 'Matched ancestors of #inner: ' + ids : 'No ancestors matched .wrapper' ); }); }); </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