Exploring the DOM API
This tutorial is part of a web programming course for people who have no programming experience.
In a previous lesson you learned about the Document Object Model, which is a hierarchical collection of objects that represent all of the HTML elements in a web page (the DOM actually includes objects that represent other things as well, I simplified it a bit so as not to overwhelm you with details, but we focused on the objects that represent HTML elements, I called them 'element objects'). You learned how to 'get a handle' on an individual element object from the DOM and assign it to a variable. Then you can use the variable, along with the dot operator, to access properties and invoke methods of the object. You also learned that most of the objects in the DOM have a common set of properties and methods. These properties and methods are called the DOM API. In a previous lesson, we spent some time exploring the Date API.
What is an API? It stands for application programming interface and it basically refers to the properties and methods of an object.
In your code, you can 'interface', or 'interact' with an object by accessing its properties and invoking its methods.
It's extremely important for programmers to be good at learning about the APIs of many various objects, because objects are the building blocks of applications.
Most of the objects that you use in a program are designed by other programmers, so you'll have to become familiar with the APIs of these objects so that you know how to use them.
There are lots of ways to learn about various APIs, but a good starting point is a reference that summarizes the properties and methods of a specific type of object.
There are many references for the DOM API, and here is one of them:
W3C DOM Reference
I like to think of an object as a tool bag, where each property and method is a specific tool that you can use to accomplish a specifig task. For example, in the last lesson you learned that you can use the innerHTML property to change the content inside an element. It takes time to learn about tools and how to use them, and many tools have quirks that you need to understand to use them effectively. You might have to hold a tool in a certain way in order get the most out of it, understanding such details comes with experience. To master methods, you should ask these questions:
- What is the purpose of the method, what task does it accomplish?
- What are the parameters that must be passed in when the method is invoked (this includes understanding the data types of each parameter)?
- What does the method return (including the data type of the return value)?
Note that you don't have to understand the code written inside the body of a method in order to use it effectively. Similarly, you don't have to understand every part that goes into making a car in order to be a good driver.
In this lesson we will focus primarily on the document object, which represents your HTML document. Remember that the root of the DOM is the window object, it represents the browser window. The document is a property of the window object. We'll also explore some properties and methods that are shared among all 'element objects'.
When you write JavaScript code that interacts with the DOM, you are primarily doing two things. First you 'select' objects from the DOM by getting handles on them and assigning them to variables. Then you can use these variables to 'manipulate' the objects.
Here is a crude reference, or summary of the properties and methods that we'll cover in this lesson:
DOM SELECTION API | |
document.getElementById(id) | Find an element by element id |
document.getElementsByTagName(name) | Find elements by tag name |
document.getElementsByClassName(name) | Find elements by class name |
document.querySelector(selector) | Selects the first element that matches the selector |
document.querySelectorAll(selector) | Selects all elements that match the selector |
DOM MANIPULATION API | |
element.innerHTML | Change the inner HTML of an element |
element.setAttribute(attribute, value) | Change the attribute value of an HTML element |
element.style.property | Change a CSS style property of an HTML element |
document.createElement(element) | Create an HTML element |
document.removeChild(element) | Remove an HTML element |
document.appendChild(element) | Add an HTML element |
Here is the HTML code that we worked with in the video, it may be handy to have it here for review:
<h1 id="main-header">DOM API Sample Code</h1>
<h3 class="sub-title">First List</h3>
<ul id="person-list">
<li>Betty</li>
<li>June</li>
<li>Jarvis</li>
</ul>
<h3 class="sub-title">Second List</h3>
<ul id="food-list">
<li>Pizza</li>
<li>Hot Dogs</li>
<li>Hamburgers</li>
</ul>
<div id="sample-div"></div>
<h3 class="sub-title">Employees</h3>
<div id="employees-div"></div>
Methods for Selecting Elements
You can use the getElementById method to select an element by its ID. The parameter that you pass into the method should be a string that matches the value of the ID attribute of the element you are selecting. The method returns an HTML Element object (I have been referring to these as 'element objects').
// STEP 1
// Get a handle on the element in the page that has an ID of 'person-list' (assign it to a variable named 'personList')
// Log the personList variable
var personList = document.getElementById("person-list");
console.log(personList);
The getElementsByTagName method takes a string parameter, which specifies the type of element that you wish to select. Remember that the name of an HTML element is called a tagName, so if you pass in "li" as the parameter then you'll get all the LI elements in the document. This method returns a special type of array, called an HTMLCollection, but for the purposes of this course you can just think of it as an array of element objects.
// STEP 2
// Use getElementsByTagName() to get all LI tags in the entire document (assign them to a variable named 'allListItems')
// Note that the variable allListItems will contain an array of element objects (actually it's a special type of array)
// Then loop through the array and log the 'innerHTML' property of each one
var allListItems = document.getElementsByTagName("li");
for(var x = 0; x < allListItems.length; x++){
console.log(allListItems[x].innerHTML);
}
Remember when I told you that all of the DOM objects that we work with in this lesson share a common set of properties and methods (a common API)? We'll we can invoke getElementsByTagName on the personList variable that we created above. In the previous example, we selected all LI elements in the entire document. In the code sample below we are selecting all the LI elements that are contained within the personList object.
// STEP 3
// Use getElementsByTagName() to get all the LI tags that are children of the of the list element object stored in the personList variable
// Then loop through these LI tags and log the innerHTML property of each one
var personListItems = personList.getElementsByTagName("li");
// notice that we just invoked the method getElementsByTagName on the personList variable, not the document
for(var x = 0; x < personListItems.length; x++){
console.log(personListItems[x].innerHTML);
}
You can use the getElementsByClassName method to select all elements that share the same value for the class attribute. The parameter that you pass in is the class attribute value of the attributes you are selecting. If you look at the HTML code above, you'll see that there are three elements that have their class attribute set to 'sub-title'. The code sample below will select them. The getElementsByClassName method returns an array of element objects (it's actually a special type of array called an HTMLCollection but you needn't worry about it for now).
// STEP 4
// Use getElementsByClassName() to get all the elements that have a 'class' attribute set to 'sub-title'.
// Store the return value in a variable named 'subTitles'
// Then loop through the array and console log each element's innerHTML property
var subTitles = document.getElementsByClassName("sub-title");
for(var x = 0; x < subTitles.length; x++){
console.log(subTitles[x].innerHTML);
}
There are two methods that are extremely powerful for selecting elements from the DOM, and you can use them in place of all the previous methods we just discussed. They are querySelector and querySelectorAll. Use querySelector when you intend to select a single element, and use querySelectorAll for selecting an array of elements.
The reason why these two methods are so powerful is that you can pass in any CSS selector as a parameter (pass it in as a string, so make sure to use quotes). Luckily you have already explored CSS selectors in this course, so you should be able to understand the code sample below.
// STEP 5
// Use querySelector() and querySelectorAll() to select the same elements that we previously selected
personList = document.querySelector("#person-list");
console.log(personList);
allListItems = document.querySelectorAll("li");
console.log(allListItems);
personListItems = document.querySelectorAll("#person-list li");
console.log(personListItems);
// OR even more efficient
personListItems = personList.querySelectorAll("li");
console.log(personListItems);
subTitles = document.querySelectorAll(".sub-title");
console.log(subTitles);
If you pay close attention to the console log after running this code sample, you'll notice that the querySelectorAll method returns a NodeList At this point I wouldn't be concerned with the difference between a NodeList and the afformentioned HTMLCollection. You can continue to think of both as simply an array of element objects. You can explore the gory details further down the road in your programming journey. If your curiosity is killing you, then you can do a google search for 'nodelist vs htmlcollection'.
Methods and Properties for Creating and Manipulating Elements
Once you 'get a handle' on an element, you can then use properties and methods to manipulate it.
The code sample below gets a handle on an H1 element and then sets properties of its style object. Remember that every element object has a property named 'style', and that the value of the style property is an object (elements are complex objects!). By manipulating properties of an element's style object you can change the CSS properties that applied to it. Note that when assigning values to the style object's properties, you use strings, which is why there are quotes around the values.
// STEP 6
// 'Get a handle' on the h1 tag in this page (it has an id attribute of 'main-header')
var h1 = document.querySelector("#main-header");
// DOM elements have a property called 'style', which is an object that has many properties
// Use dot notation to change the following properties of the style object:
// set the fontSize property to "18px"
// set the color property to "midnightblue"
// set the backgroundColor property to "red"
// set the padding property to "15px"
// set the borderRadius property to "10px"
// NOTE: You could 'cache' the style object for more efficient code
h1.style.fontSize = "18px";
h1.style.color = "midnightblue";
h1.style.backgroundColor = "red";
h1.style.padding = "15px";
h1.style.borderRadius = "10px";
You can create elements in your JavaScript code and then insert them into the DOM. This will cause them to appear in the web page when the code executes. To do this, first use document.createElement to create an element. The parameter should a be the tag name of the element you want to create (a string). This method returns an element object. Next you need to get a handle on the element to append it to. This will element will act as the container for the element you just created. Finally invoke the appendChild method on the container and pass in the variable that stores the created element. Here's the code to do all that:
// STEP 7
// Create an 'input' element
// Set its 'type' attribute to 'button'
// Set its 'class' attribute to 'btn-standard'
// Set its 'value' attribute to 'CLICK ME'
// then use appendChild() to add it to myDiv
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("class", "btn-standard");
btn.setAttribute("value", "CLICK ME");
var sampleDiv = document.getElementById("sample-div");
sampleDiv.appendChild(btn);
After creating the INPUT element, we used the setAttribute method to add attributes to it. We controlled the appearance of the button by setting it's class attribute to "btn-standard". This is a different approach from the previous example which manipulated the style property of an element. Here is the CSS code from the sample file that defines the .btn-standard ruleset:
.btn-standard{
background-color: midnightblue;
border-radius: 10px;
color:white;
}
For a preview of what's coming up next, here's how you could make the button do something when it's clicked:
btn.x = function(){
alert("Thank you for clicking me");
};
We'll talk more about this code in the next lesson, but for now you can just note that it assigns a function to the x property of the buton. And that the function will be invoked when the button is clicked.
Data Binding
Finally, I want to finish off this lesson with a code sample that may prove to be very important in your programming career. I breifly mentioned that programs often fetch data from a database, then convert the data into an array of objects. Let's assume that our program has done that already, and this is the array of objects that we have to work with:
var employees = [
{firstName: "Bob", lastName: "Smith"},
{firstName: "Betty", lastName: "Jones"},
{firstName: "Jenna", lastName: "Frank"}
];
Next we need to display this data on the web page, so we'll use some of the selection and manipulation techniques that have been described above. I outlined each step in the comments below.
// To display the employee data in a list...
// First create a UL element
// Then loop through the employees array
// In the body of the loop do the following:
// Create an LI element
// Set the innerHTML property of the LI to the first and last name of the current employee
// Append the LI element to the UL element
//
// After the loop, get a handle on the DIV element in the HTML that has an ID of 'employees-div'
// Then append the UL to to the DIV
var ul = document.createElement("ul");
for(var x = 0; x < employees.length; x++){
var li = document.createElement("li");
var emp = employees[x]; // 'cache' the current employee in the emp variable
li.innerHTML = emp.firstName + " " + emp.lastName;
ul.appendChild(li);
}
var employeesDiv = document.querySelector("#employees-div");
employeesDiv.appendChild(ul);
Displaying information like this in the browser window is known as data binding because it 'binds' data to the user interface. As a programmer, you'll most likely be doing a lot of data binding, and we'll exlplore it more in an upcoming lesson.
NEXT LESSON: Events