Created
August 12, 2015 06:05
-
-
Save nicksheffield/3fec28c2d7cb93a0c33c to your computer and use it in GitHub Desktop.
Basic jQuery DOM Traversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>DOM Traversal</title> | |
| <style> | |
| .box1, .box2, .box3, .box4, .box5{ | |
| border: 1px solid black; | |
| padding: 1em; | |
| background: white; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>DOM Traversal</h1> | |
| <div class="box1"> | |
| 1 | |
| <div class="box2"> | |
| 2 | |
| <div class="box3"> | |
| 3 | |
| <div class="box4"> | |
| 4 | |
| <div class="box5">5</div> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <script src="bower_components/jquery/dist/jquery.min.js"></script> | |
| <script src="script.js"></script> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $(function(){ | |
| $('.box3').css('background', 'yellow'); | |
| // .parent() goes up one level | |
| $('.box3') | |
| .parent() | |
| .css('background', 'blue'); | |
| // you can use .parent() multiple times | |
| $('.box3') | |
| .parent() | |
| .parent() | |
| .css('background', 'lime'); | |
| // closest gets the first parent that matches | |
| // the selector | |
| $('.box3') | |
| .closest('.box1') | |
| .css('background', 'lime'); | |
| // children gets all the direct children | |
| $('.box3') | |
| .children() | |
| .css('background', 'magenta'); | |
| // find gets all the descendents | |
| // that match the selector | |
| $('.box3') | |
| .find('.box5') | |
| .css('background', 'cyan'); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment