Intro to the DOM

Learning Competencies

By the end of this section, you should be familiar with and able to:

  • Explain the basics of the DOM

Time Box

ActivityTime
Intro to the DOM30 minutes

Intro to the DOM

This section will walk you through some of the basics of the DOM. Follow along in your code editor and browser to investigate your questions as you go.

HTML and CSS are two of the fundamental languages found almost everywhere on the web. The Document Object Model provides the means to interact with objects in an HTML document.

When using JavaScript to manipulate HTML elements on a page , we need a way to get hold of specific elements to do things with them.

Browsers provide a document JavaScript object with a large number of properties and methods to allow us to do precisely this. It's a "tree" of objects, with JS objects representing the head, body, title, paragraphs, etc. It's like a family tree, except each object, method, or property has only one parent.

At the head of this tree-the great-great-great-grandparent of all the rest, so to speak - the original ancestor - is the window object, and inside the window object is the document object, which represents our page. For now, we're only going to worry about the document object.

You can see this when you open the Chrome Developer Tools console and type document. (don't forget the period after it) and wait for a second, Chrome will pop up a long list of properties, methods, and objects that are the "children" of the document object.

Note: You'll learn more about the DevTools later this sprint. To access the console tab, press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux).

Document dropdown in Dev Tools

Figure 1: What's inside the 'document' object.

If we consider the page, we can imagine the document object like this (but with a lot more elements inside it, right?):

HTML5 DOM tree

Figure 2: A simplified view of the 'document' object.

In the example above, the <body> element has 2 children, an <img> element, and a <p> element. The text in the <p> element is a child of that <p> and so can be accessed and manipulated directly.

Break time

Take a short break to let this information sink in. Post questions or blocks on Discord so your cohort and online community can help you. Continue onto the next block when you feel ready to.