Jacob Ruiz

View Original

Mastering Javascript Fundamentals: Recursing Through the DOM

Get the fundamentals down and the level of everything you do will rise. - Michael Jordan

As stated in my original post, I do 1 hour of video lessons from Watch and Code every day. If you're interested in learning Javascript in a way that goes beyond basic tutorials and gives you a foundational, practical knowledge without relying on frameworks - I'd highly recommend it. If you're reading these posts, please keep in mind that these are just my notes, and I'm not an expert (yet!). If your goal is also to master the fundamentals of Javascript, please head over to Watch and Code and start your journey there!

All screenshots were annotated using Shotty.


My notes today are less thorough than usual. It's Saturday, and in the interest of time, I've focused on understanding the code examples myself, and I've spent less time documenting. Below are the somewhat scattered notes of key points in today's exercise.

chainIsGood example:

Recursion is good for problems that have an unknown level of layers or depth.

You need at least 1 base case, but you can have more.

Recursively processing DOM nodes

Similar problem of unknown depth.

Elements in the DOM can be nested.

See this content in the original post

Can be simplified to:

See this content in the original post

Can be simplified even further to:

See this content in the original post

We can tweak this function to be more useful by accepting a callback, so now we can run any function we want on the DOM elements:

See this content in the original post

Now we can print each element like before:

See this content in the original post

Or we can just print the tag name:

See this content in the original post

Summary

  • Recursion is a great technique for working with the DOM, since the DOM has unknown levels of depth, and lots of nested elements.
  • We can create a function forEachChildElement that runs a callback on each element of the DOM.