Well, that’s exactly what we’ll be covering in this post. You’ll finally understand what the heck your smug developer friend is talking about next time he decides to throw a casual “DOM” around at your next meeting.
Sound good? Read on…
Enter “the DOM”
Well, what the heck is the DOM anyways? Well, first of all, DOM stands for Document Object Model.
OK, great. But what does that all mean really?
Let’s break that down a bit though…
Picture a tree with lots of branches going upwards to the sky. Well, the DOM is a lot like that. In fact, you could say that the DOM is in fact, a virtual tree that’s created from all your source code.
A real code example
Let’s say I had a simple HTML file that looks like this:
Here is what this would look like once the browser runs this block of code and creates a little DOM tree for us:
As you can see, your tree has a bunch of different branches that each extend as children of other branches. And at the end of each branch is an
html tag (e.g.
li, etc). We could say these make up the leaves of our little tree.
Now, of course, these trees can get pretty massive. Just imagine a massive web app or complicated website (e.g. Facebook).
However, no matter how big or small your DOM tree, they all start out the same: The
document is the root and it’s where all your HTML tags start branching out from. We’ll talk a bit more about this mysterious
document root on another post, but just understand for now that every DOM tree starts with this as the base and then uses all your
html tags to create the branches and leaves of your DOM tree.
One important point: The DOM is NOT just your .html file!
For the longest time, I used to confuse the DOM with my actual source code (the code you write in an HTML file for example).
However, the DOM is not exactly just the HTML code you write.
Here’s an example to help you understand things better. Let’s pretend I have an HTML file with
p tag in the body and nothing else. This paragraph has a class called ‘blue.’
Now, inside my CSS file, I have a class called
blue that will show the paragraph in blue.
No biggie, right?
HOWEVER, I also have a CSS style for a paragraph that contains both the class
active. This style will not only turn the paragraph blue, but it will also underline it.
Let’s use a live pen demo so you can see how this works:
Just take my word for it for the time being, but those two lines ADD a CSS class called ‘active’ to our existing paragraph with a class ‘blue’. In other words, the “picture” that the browser will finally end up “painting on screen” once the page loads will now have TWO classes: