Traversing the DOM Tree
Understanding the concept of traversing the Document Object Model is incredibly important when it comes to manipulating elements so you can do whatever you want with them. I had a very rich and frustrating lesson recently in regards to locating and using elements correctly. Locating the elements in relation to their parents, siblings and children enables you to be able to move elements around, style elements when events occur and generally do really cool stuff. I found out there are subtle but important differences between the declarations of getElementsByClassName and querySelectorAll. Class gives you an HTML collection and SelectorAll gives you a node list. The way you utilize these are different. The HTML Collection lists all the elements with indexes and is an array like structure, which is updated every time something changes with text, elements, etc... Think of it like sitting down to write a letter on a piece of paper. Every time you make a mistake, you can erase it and rewrite it, it is a living document, the same with the HTML collection. Querying by all gives back a node list with indexes as well, but this one doesn't update like the collection mentioned above does. This is static, I like to think of this like sitting down to write something on paper, and you take a picture. Once the picture is taken, the paper doesn't ever change. This helps me visualize the difference between the two. Then there are several ways of choosing elements, parent, sibling and children. With all types you can choose between nodes or elements. parentElement, children and elementSiblings all give back elements only. parentNode, childNode and previousSibling/nextSibling give back text, comment or element nodes. This also includes whitespace. Be aware of this difference, otherwise it may have you chasing your tale for the next half-hour. Ask me how I know! Moving up and down the DOM tree effectively comes only one way, with practice, time and resolve. I'm not there yet, but I am getting better everyday.
Subscribe to my newsletter
Read articles from Taneka Blair directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Taneka Blair
Taneka Blair
Software Engineer. ๐ป Doing a SWE โ๏ธ summer internship. Graduated from Code Platoon. ๐๏ธ