JavaScript DOM Objects

This tutorial is part of a web programming course for people who have no programming experience.


A Quick Review of Objects

We've been spending a lot of time learning about objects in JavaScript. Here's what we know about them up to this point:

  • We can use objects to simulate objects in the real world (and to simulate virtual objects, such as dates and emails). We can create objects to 'model' the data we are working with. We created objects to represent each dog that we may track in a program. If you've been doing the worksheets, you created book objects that might be used in a library tracking system. You also created an object that simulates a bank account, and keeps track of simple transactions.
  • Objects are more than just properties. We can make them DO things by adding methods to them.
  • Objects can become very complex. That is, an object can be made up of many other objects. For example, we created a 'computer' object that had a 'hard drive' property. The hard drive, nested within the computer, was itself an object with it's own set of properties. This is how complex systems are put together in the real world! Various objects are used as parts in assembling other objects. Just think of all the objects and components that go into making an automobile.

Now that you know the basics of objects in JavaScript, I can tell you that a web page is full of objects.

The Document Object Model

When a web page is loaded into the browser, there is a tremendous amount of work being done under the hood. The browser converts each and every HTML element into an object, and all of these objects together are used to make a model that simulates the entire web page. This model is stored in the memory (RAM) of the computer and it is known as the Document Object Model. We can use use JavaScript code to manipulate any object in the DOM, and the changes will automatically be reflected in the browser window.

We refer to these objects as nodes, so a node is an object that represents an HTML element on your page. Nodes can represent other things in the HTML as well, such as the text that is inside an element, but for this lesson we'll stick with nodes that represent HTML elements. I like to call them element objects, although that may be a term I made up. All element objects have some things in common with another. They all share a common set of properties and methods. So if you understand how to work with an element object that represents an LI element in the HTML, you also know how to work with an element object that represents an H2 element. This makes things a lot easier, because you don't have to worry about an LI object having completely different properties and methods from an H2 object. Here is a page that shows the properties and methods of element objects. Have a look at this link and you'll quickly realize that every element object is complex, and loaded with properties and methods that we can use in our JavaScript code. This puts a lot of power into your finger tips as a JavaScript programmer.

The DOM is a hierarchical data structure, which you should be familiar with from the lessons on HTML. This makes sense because as you already know, an HTML document is hiearchical and since the DOM simulates, or 'models' an HTML document, it follows a heirarchical structure as well. The root of the DOM is an object that represents the browser window, and this is very fittingly called the window object. Because the window object contains all of the other objects that make up the DOM, it is extremely complex. Let's go ahead and log the window object so that you can see what I mean:

console.log(window);

Remember that the browser creates the entire DOM when it loads and reads (parses) the HTML code in a web page. You do not have to declare and initialize the 'window' variable in your JavaScript code because the browser does it for you when it creates the DOM. If you look in the console after running this code you should be able to inspect the window object in the console. You'll see that it has many, many properties and methods in it. Many of the property values are objects themselves, which is what makes the window an extremely complex object.

If you spend enough time inspecting the window in the console log, you'll see that it has a property named document, which represents your HTML document sitting inside the browser window. Within the document object, you can find objects that represent each of the HTML elements that are in the HTML code. You can log the contents of the document object like this:

console.log(window.document);

Take a moment to inspect the properties and methods of the document object. There is one method in particular that we will make heavy use of in our JavaScript code...

The document.getElementById Method

If you want to use JavaScipt to manipulate an element in your HTML code, you can use the document.getElementById method to store the element object in a variable. In order for this to work, the HTML element must have an ID attribute. Let's assume that your HTML code includes this element:

<h1 id="main-header">The DOM (Document Object Model)</h1>

Notice that the ID attribute of this H1 element is set to a value of 'main-header'. This value can be passed in as a (string) parameter when invoking the document.getElementById method like so:

var mainHeader = document.getElementById("main-header");
console.log(mainHeader);

In this code sample, the variable mainHeader is storing an object that represents the H1 element in the sample web page. The document.getElementById method returns the element whose ID attribute value matches the parameter Once you have the element object assigned to a variable, you can use the dot operator to access its properties and invoke it's methods.

You might be wondering why the above code sample doesn't look like this:

var mainHeader = window.document.getElementById("main-header");

This code would work without any problems, but you don't need to specify the window object because it is the root element, and everything in both the DOM and your JavaScript code is considered to be inside the window object. Therefore it's implied, and you can omit it. I don't mean to confuse you at this point, but take look at this example and it may help to demonstrate that everything, including the variables that you declare, are considered to be inside the window object:

var firstName = "Bob";
console.log(window.firstName);

One property that we'll use a lot when working with element objects is called innerHTML. It contains all the HTML and text content that is nested within an element. Let's console log the innerHTML property of the H1 element object that is being stored in the mainHeader variable:

console.log(mainHeader.innerHTML);

Now let's change the value of this property:

mainHeader.innerHTML = "I <b>LOVE</b> JavaScript!";

When you refresh the page and this line of code executes, you'll see that you have altered the contents of the H1 element.

Suppose you have this list in your HTML code:

<ul id="topics-list">
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>

Here's another code sample that demonstrates the innerHTML property, this time we have a handle on a UL element:

var topicsList = document.getElementById("topics-list");
console.log(topicsList.innerHTML);

topicsList.innerHTML += "<li>Python</li>";

In this example, we concatenated another list item into the unordered list. This code will add an LI element to the UL element in the HTML.

You can access the tagName property to see what type of element you have a handle on:

console.log(mainHeader.tagName);

Attributes In HTML Code Become Properties of Element Objects

When you get a handle on an element, its attributes become properties of the element object. Consider this HTML code:

<img id="imgDog" src="../images/happy-dog.jpg" alt="Picture of a happy dog" />

If you look up the words 'attribute' and 'property', you'll find that they are synonyms. And hopefully you can see how they they are closely related in HTML and JavaScript. For some reason, I'm not sure why, they are referred to as 'attributes' in HTML, and 'properties' in JavaScript. If you really dig deep into JavaScript, you might find a slight difference between an attribute and a property, but we won't get into those gory details in this course.

Now let's get a handle on this IMG element and log a few of the object's properties:

var dogImg = document.getElementById("imgDog");
console.log(dogImg.id);
console.log(dogImg.src);
console.log(dogImg.alt);

You could also use the getAttribute method, which takes a (string) parameter that reresents the name of the attribute that you wish to get:

var pathToImg = dogImg.getAttribute("src");

You can alter the attributes/properties in one of two ways in your JavaScript code:

dogImg.src = "../images/angry-dog.jpg";
// or
dogImg.setAttribute("src", "../images/angry-dog.jpg");

As you can see, you can update the src of the HTML by either changing the src property of the element object, or by invoking the setAttribute method. Note that when you call setAttribute you should pass in two parameters, the first is the name of the attribute you wish to update (a string), and the second is the value you wish to set it to. It's pretty common in many programming languages to offer more than one way to accomplish a task. This can be confusing for beginners, but it gets easier with experience.

The Style Property of an Element Object

Every element that you get a handle on will have a style property, which is an object that contains properties for controlling the CSS properties applied to an object.

mainHeader.style.backgroundColor = "blue";
mainHeader.style.color = "white";
mainHeader.style.fontSize = "30px"

This example demonstrates how you can manipulate the CSS properties that are applied to an element. It also further demonstrates how every element in a web page is a complex object, and the style property (which every element has), is an object made up of properties. Note the use of quotes when assigning values to the properties of the style object, you should use strings when updating the style of an object in your JavaScript code.

It's important to note that in CSS code the property names often have dashes in them, and if you wanted to control the main header from your CSS code, you could do it like this:

#mainHeader{
	background-color: blue;
	color: white;
	font-size: 30px;
}

In JavaScript, property names cannot have dashes in them, so the property names of a style object use camelCase. It's not uncommon to alter CSS properties with JavaScript code, and it can be done to make web pages highly interactive by changing it's appearance based on what the user does.

Summary

This is a big moment in your web programmning career! You are beginning to use JavaScript code to interact with the HTML elements in a web page. There are so many more properties and methods of element objects that we did not discuss in this lesson. Remember that all element objects that you 'get a handle on' will share a common set of propeties and methods. So if you know how to work with one element, you can work with all of them. In an upcoming lesson we'll explore more of them, and you'll learn other ways to control the behavior of a web page with your JavaScript code.

NEXT LESSON: ...