Codepath

DOM

The DOM is a programming interfaces for HTML and XML documents. This basically means that it helps represent the structure, style, and content of a document, in our case our HTML document, in the form of objects.

What is the DOM?

You may be thinking, why is it important to represent the HTML elements in the form of objects? You may have experience in an object-oriented programming language: Java, Python, C++, Ruby, Scala, and many more. "Objects" contain data that have attribute, properties, and methods.

We already have seen some attributes of HTML elements in our previous lab.

  • The img element have attributes src, alt, width, height, and more.
  • All HTML elements share global attributes including id, class, style, hidden, and more.

Using the DOM and JavaScript, we can apply methods to modify how an element behaves. We will explore how to do this in this lab.

The DOM can be represented by a tree structure where the leaves or nodes of the tree each represent an HTML element. Let's take a look at an example code

Image of DOM tree

index.html
	<html>
		<head>
		  <title>My Document</title>
		</head>
		<body>
		  <h1>Header</h1>
		  <p>Paragraph</p>
		</body>
	</html>

The DOM is not a programming language. It used to connect/access the document, HTML file, and its elements.

Traversing the DOM

You don't have to do anything special to use the DOM. It is a staple in web development and is already loaded into popular browsers. We access the DOM by using the keyword document.

There are multiple methods that can be used in our JavaScript file that calls upon the DOM to create references to HTML elements.

  • document.querySelector(selector): Finds HTML elements that match the selectors. When using this method, selectors are written in a similar manner as CSS selectors. Remember that # indicates the id name and . indicates the class name of an element. This will only return a single element. If there are multiple elements that match the same selector, only the first element will be returned.
  • document.querySelectorAll(selector): This works similarly to the querySelector method but returns all elements that match the selector.
  • document.getElementById(idName): Finds the single element that matches the id name.

You may notice that in each of these options, it is incredibly important to utilize the id and/or class attribute to identify a single element.

Fork me on GitHub