Family Tree Revisited – Intro to jQuery

With the help of jQuery selectors, you can select specific elements of the DOM. But, what if you wanted all the children of this div? How would you find them? Alternatively, what if you selected this div, but you wanted to inspect its parent element, this div? How would you find it? jQuery gives us DOM traversal methods for moving around the DOM tree. I’ll start with parent. If I’ve selected the node with the ID Cameron, I can select my immediate parent by calling .parent. Dot parent goes up the DOM one level, so at this point I’ve selected the element with the ID Mark Suzanne. I could use .parents to select my parents, my grandparents, and my great grandparents. I could also filter for a specific parent by passing in another selector to the parents method. Say, for instance, I just wanted my grandparents, JerryJudy, I could pass JerryJudy with a pound sign into parents and then only have this node selected. It’s important to note that parent will only go up a single level on the tree. If you need to go up more than just one level you need to use .parents; which will go all the way up to top of the DOM tree. I could go down the DOM too and select my children using .children. Dot children creates a jQuery collection of all of my immediate children, meaning that they’re one level down in the DOM. But if I wanted my children’s children, or any children of Taylor and Grant, if they existed in this example, I would have to use .find. Dot find goes down the DOM more than one level. Similar to parent and parents, jQuery provides a method that only traverses a single level deep in the tree, which is called .children. If you want to go deeper, there’s a separate method called .find which will go many levels down on the DOM tree. Finally, there’s .siblings. Dot siblings returns a jQuery collection of all of my siblings, meaning that we’ve got the same parent. In this case, Max and I both have the same parent so calling .siblings would return Max. And once again, I can pass a selector into siblings if I need to get more specific with my selection. Now, I want you to try out all of these DOM traversal methods with a quiz.

Add a Comment

Your email address will not be published. Required fields are marked *