JavaScript for Complete Beginners – Session 2 – A Tour of DOM

Welcome back to Session 2 of Module JavaScript – JavaScript for Complete Beginners.


In Session 1, we accomplished the following:

  • Defining the overall goal of this module, which is to build an “advanced calculator”
  • Taking the first step with JavaScript, which is to “print something”
    • In browser JavaScript console, with a brief tour of how to use it
    • Writing an HTML file with embedded JavaScript, which prints to the page when opened in the browser.

In this session, we will continue to push forward toward building a calculator. Specifically, we will move toward “drawing” the calculator on the screen with JavaScript (i.e. a more complex “print something” on the screen).

Visualize the Calculator

Although we all know what a calculator looks like, it’s important that we can visualize it with enough details for us to know what to code. On my computer, the following is the look of the standard calculator and a scientific calculator on my computer.

As we can see, there are the following elements:

  • A display that shows the current value (whether typed or calculated)
  • Buttons for inputting the numbers (09, ., -)
  • Buttons for inputting the equations (+, -, *, /)
  • Buttons for getting results (=)
  • Buttons for memory slots (M+, M-, C, CE)
  • Buttons for advanced formulas (sin, cos, tan)

For us to build out a calculator, the goal then is that at a minimum we need to replicate the standard calculator. Our next step is to figure out how to “print” the calculator onto the screen with JavaScript. Given that we are just starting to learn how to programming, this can be a tall order, but let’s take it step by step. Let’s figure out how we can print out a single button.

Let’s Play With Developer Tools A Bit More

In order to print out a single button with JavaScript, we will need to continue to get familiarize with our programming environment. As stated before, your browser is a full-fledged programming environment, and we do ourselves favors to leverage it to the max for learning purposes.

Let’s open up our index.html from Session 1, and let’s load it up in Chrome. You’ll see that Hello world! This is printed by my JavaScript code! showing in big bold letters in the browser.

If we right click on the page and then choose inspect, it’ll open the Developer Tool, which we looked at the Console tab in Session 1. This time, let’s take a look at the Element tab.

In the Element tab, you will see what looks like your current HTML code, except that it’s not just text, but rather actual structure that maps to the HTML. You can expand / collapse the elements that have children elements to show / hide them.

As you move your mouse cursor over one of the elements, you can actually see the corresponding element in the browser window getting “highlighted”. Chrome is trying to be extremely helpful to you as a developer, so you can orient yourself.

Furthermore, you can change the html in the page from inside the Elements tab. For example, you can change the text of an element:

You can change the color of an element:

You can even add a new element:

All these are made possible, because of something called DOM (Document Object Model).

What Is DOM (Document Object Model)

When the browser opens an HTML and tries to show what the page looks like, it basically creates an memory-representation of the HTML document, so that the browser can manipulate it easily. The memory representation is called DOM, and when we are changing the text, the color, and add elements through the Developer Tool, we are in effect making changes to the DOM, which causes the browser to “redraw” the document to reflect the changes.

We can use JavaScript to achieve the same effect. After all, you won’t be in front of your users to make changes to the DOM through the Developer Tool for them, so you want your program to do it for you. Let’s learn how we can make changes to the DOM through JavaScript.

DOM is what’s known as an API (Application Programming Interface), basically a document set of methods, approaches, to accomplish a goal / operation via programming, which in this particular case, it’s the official way for you to programmatically interface with the HTML page loaded into the browser.

So let’s get started to see how we can program DOM.

Again, the developer tool can give us a lot of hints. Let’s try to type slowly the word document into the Console. After a couple of characters, you should start to a list of potential matches showing up right underneath your typing. This is Chrome trying to be helpful to you, and this particular feature is known as intelligent code completion.

It can go further too, after you typed out document, type ., and then see a new list populated.

The reason that there is a new list showing up is because document is what’s known as an object, which is a structure that have additional properties and methods that can be accessed via the . operator in JavaScript.

We will give a more formal treatment of some of these concepts in the next Session. What dealing with abstract concepts, it’s always good to start with a concrete example.

Developer Tool’s code completion basically help us to discover what are the available properties under an object after we type in the . operator. That helps you narrow down what you are looking for very quickly.

Though, since we just get started, it’s still quite overwhelming to just see that list, and we don’t know most of them. That’s completely okay. Nobody remembers the whole list. Instead of trying to memorize the API, developers learn to see the patterns in the API, and then use that to guide them toward finding what they want.

For example, earlier we were able to make change to the text of an element, that means the following:

  • We must be able to identify a particular element programmatically (without which, we cannot know which element we are changing).
    > Remember, all GUI does is to trigger the underlying code. I.e. when we are hovering over an element, there is code written that holds the reference to that element and then “make it highlight”.
  • There must be a property (or method) on the element that we can make changes to in order to change the text, the color, or anything else.
  • There must also be a way to create new elements as well, and then add it to the right location within the document object model.

With the above knowledge, we now know what the API must support, and hopefully it does so in a “sane” way, i.e. the name of the properties / methods that we need hopefully would be similar to what we just said above, instead of something completely different. I.e.,

  • identifying the element – there ought to be methods with names like get or find the element.
  • changing the color would hopefully involve a property that has some name similar to color (that gives you clue what to look for in the code completion).
  • changing the text – the same, a property or method that has a name that make you think of the text, like text, content, value, etc.
  • adding an element – there ought to be methods with names like add or append an element.

So, let’s see how we can find a particular element, let’s find the p element that we added.

There are quite a few methods that can be used to get an element. The one that we will use for now is getElementsByTagName.

var paragraphs = document.getElementsByTagName('p'); // return an array of elements that have the tag name 'p'
var elt = paragraphs[0];

What does the above code mean?

  1. we declare a variable called paragraphs (notice the plural), and we assign (=) the value from the function call of document.getElementsByTagName('p') to it.
  2. we then declare another variable called elt, and then we assign the “0th” item of the paragraphs to it.

Notice how much longer the equivalent English is compared to the code? A lot of beginners want to code in English, hopefully this helps reduce that thought.

We haven’t talked about any of these concepts at all, so let’s give it a quick shot.

What Is a Variable

Remember in the last session we talked about identifier? An identifier is a name that allows you to reference what’s referred to by the name. Although we didn’t explain it too much, we can more or less think of it as an “address” of a mailbox, so when we are using the identifier, we know which mailbox we are talking about so we can retrieve the content inside the mailbox.

If an identifier is the address of a mailbox, then a variable is a newly created mailbox with a new name that you just give it.

So in the code above, we created two new “mailboxes”, one named paragraphs, and the other named elt, and we use = to put things inside those mailbox. Then as long as the mailboxes are still “visible” (a mailbox can become invisible when it gets destroyed, or when it gets hidden by another mailbox with the same name – we will talk about this later), you can refer to what’s inside by the name of the mailbox.

If you ever wonder why you need to create a variable – the reason is that you might want to do something with the value held by that variable later. You don’t need to create a variable for a value if you don’t have such a need, i.e.


is also valid, but you won’t be able to work with the values returned by that function call.

What Is An Array

The value returned by document.getElementsByTagName('p'); is what’s known as an array, which can be thought of as a “list” of things.

Strictly speaking, the value returned is like an array, but not exactly an array. The distinction doesn’t matter for us at this time, but I mention this just so you won’t get surprised as you get further when it comes up.

What is specific about arrays is that they have the following behaviors:

  • There is a length property that tells you how many elements exist in this array.
  • You can access the individual elements inside the array via a numeric index, as long as the number is between 0 and length - 1, with the first element starting at 0.
  • The way to access the element is via the [] operator.

Therefore, in the above code, we first assign the resulting array to the paragraphs variable, which means that paragraphs variable now holds an array, whose items can be accessed by []. so when we type

var elt = paragraphs[0];

We are accessing the first element inside the array.

We could write code like that above because we know for certain that there is one p element in the DOM, and this code might not work for other DOM. As we get better at writing code, we want to write code that can work in many situations so we will need to account for potential differences.

Once we have the element, we can then try to do things with it. For example – to change the color, we will need to work with the style property (this is the property manipulated by the infamous CSS). = '#ff0000'; // change it to RED in RGB scheme.

To change the text, we can use the textContent property.

elt.textContent = "This is the new text";

To add a new element – after all, we are very interested in creating buttons, we utilize document.createElement and then appendChild on the element that we want to add it to.

var button = document.createElement('button');
document.body.appendChild(button); // until we have a better place, put the element under the body element will make it visible.

Also remember, a button created this way will look very “skinny” as it doesn’t have any text.

button.textContent = "Click Me";

Awesome! Now that we know how to create a button, we can create all of the buttons needed by our calculator.

What Happens When We Click on the Button?

Having a button is nice, but we need to go further – we want the button to do something when we click it. If you try to click on the button now, you’ll see that besides showing that you have clicked it, it doesn’t do anything else. And that’s because we haven’t told it to do anything yet.

Software basically only do what they are programmed to do, i.e. all features and bugs are programmed in (bugs are unexpected outcome of the program).

In order to make the button do something, we need to add what’s known as an event listener to the click event.

We will cover this concept in more details later, for now, just know that when there is an event, and if there is an event listener for the event, the event listener will get called.

An event listener is a function that listens to a particular event, in this particular example, it’ll be a click event on the button element.

button.addEventListener('click', function () {
  // let's just do something we know how to do, let's change the color of the paragraph. = '#00ff00'; // change it to green.

Now when you click on the button, voila, the element’s color is now changed! With the ability to handle events, it means that we now also know how to handle the users clicking on any of the calculator buttons, we just need to put everything together.


There are quite a few concepts we go through quickly in this chapter. In this chapter the goal is to show what’s possible, so that programming doesn’t look like magic. We have learned how to navigate around the Developer Tool, and we have succeed in manipulating the DOM, as well as hooking up event listeners to perform operations based on user triggered events like clicks. We will revisit them in subsequent chapters in more details to help solidify the understandings.

Leave a Reply