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 - parent() 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; } .wrapper { display: flex; gap: 40px; } ul { list-style: none; padding: 12px; border: 2px solid #3949ab; border-radius: 6px; background: #ffffff; width: 160px; } ul.food-list li, ul.drink-list li { padding: 10px; margin: 6px 0; background: #e8eaf6; border-radius: 4px; cursor: pointer; transition: background 0.2s; } ul.food-list.highlight { background-color: #ff0ff0; /* light green */ } ul.drink-list.highlight { background-color: #ffe0b2; /* light orange */ } .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>parent()</code> Method</h1> <p>Click any list item below. Only when its immediate <code>ul</code> parent matches the selector <code>ul.food-list</code> will that container highlight, demonstrating how the optional selector filters the result.</p> <div class="wrapper"> <ul class="food-list" id="foodList"> <li>Pizza</li> <li>Burger</li> <li>Sushi</li> </ul> <ul class="drink-list" id="drinkList"> <li>Tea</li> <li>Coffee</li> <li>Juice</li> </ul> </div> <div class="info" id="infoBox">Click an item to test <code>parent('ul.food-list')</code>.</div> <script> $(function() { $('ul li').click(function() { // Remove any existing highlights $('ul.food-list, ul.drink-list').removeClass('highlight'); // Get immediate parent filtered by 'ul.food-list' var $foodParent = $(this).parent('ul.food-list'); if ($foodParent.length) { $foodParent.addClass('highlight'); $('#infoBox').text('Matched parent container: #' + $foodParent.attr('id')); } else { $('#infoBox').text('No match: parent is not ul.food-list.'); } }); }); </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