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 closest() – Multiple Click Targets 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: 25px; } .box { padding: 15px; margin: 20px 0; border: 2px solid #3949ab; background-color: #e8eaf6; border-radius: 5px; } .highlight-target { border: 2px dashed #1e88e5; background-color: #e3f2fd; padding: 15px; margin-top: 10px; } .clickable { background-color: #9fa8da; padding: 10px; margin-top: 10px; border-radius: 4px; cursor: pointer; } .highlight { background-color: #ffe082 !important; /* yellow highlight */ } .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>closest()</code> Method</h1> <p>Click either box to see how <code>closest('.highlight-target')</code> returns the nearest matching ancestor for each element.</p> <div class="box"> <strong>Section A</strong> <div class="highlight-target" id="targetA"> <div class="clickable" id="clickA">Click Me (A)</div> </div> </div> <div class="box"> <strong>Section B</strong> <div class="highlight-target" id="targetB"> <div class="highlight-target" id="innerTargetB"> <div class="clickable" id="clickB">Click Me (B)</div> </div> </div> </div> <div class="info" id="infoBox">Click any box to check closest matched ancestor.</div> <script> $(function () { $('.clickable').click(function () { $('.highlight-target').removeClass('highlight'); const closestMatch = $(this).closest('.highlight-target'); closestMatch.addClass('highlight'); const id = closestMatch.attr('id'); $('#infoBox').text( id ? 'Closest matched ancestor: #' + id : 'No matching ancestor found' ); }); }); </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