JavaScript: Intro to Using the DOM

Patrick Pierre
11 min readOct 6, 2020

--

Photo by Glenn Carstens-Peters on Unsplash

So you can create a string and save it to a variable in JavaScript, that’s cool and all but how does that actually help you get started on using your newfound JavaScript skills on a real website?

Assuming you already learned the basics of html and css, the answer to the question is by using the Document Object Model (DOM). In this blog post I’m going to tell you all about what the DOM is and how you can use it in combination with JavaScript to make your websites or apps more dynamic.

I will also be giving you acccess to a simple application I made to help you understand more about what you can do with the DOM.

What is the DOM and why should I care about it?

The creation of any good website or application involves two things: Front-end Web Developement and Back-end Web Development.

The front-end is responsible for how your site looks and how the user interacts with it; the back-end is responsible for dealing with everything else in your site such as working with the database to store user information, site security, etc.

The DOM allows you to use JavaScript to make changes to your front end.

According to MDN Web Docs, The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document — such as the HTML representing a web page — in memory. What this means is that the DOM acts as a bridge between your html document and your JavaScript code.

What does the DOM actually do?

The DOM converts your html document into a data structure called a Tree with each html element as a node in that tree. You don’t have to worry about the specifics for now but basically because your html is converted into a bunch of nodes (objects), it allows for JavaScript to interact with it. JavaScript treats that node as if it is an object with key-value pairs.

The most important takeaway here is that the DOM allows us to write JavaScipt code that can make changes to our html document.

With this fact alone, we can start to use JavaScript to make our websites and applications much better.

Let’s Build Our DOM Application

Below I will embedding a small applicaton that I made on Codepen which is an online code editor. The application is very simple so it makes for the perfect start for us to get more familiar with the DOM. The application is called, “Simple To Do List”, and it allows you to….make a to do list.

I know, it sounds too simple but trust me, it is a great place to get started with the DOM. Feel free to open your own code editor and play around with the code provided or just follow along.

Simple To Do List App

I will use examples of code from this app to discuss the two of the most important things you can do with the DOM:

  1. Create and Delete html elements from your web page
  2. Make use of the addEventListener() method

Overview of the Simple To Do List App

In order to help us learn more about what we can do in this application we will be mostly focused on the JavaScript and html code used.

As you can see from just looking at the app, the user is able to enter things in and press the “add to list” button. Doing this will allow for whatever the user entered in to be added to the box below the button. Also please note that at the bottom of the box there is a button called “clear list”. Pressing this will delete every list item that we create inside this box.

If you take a peak at the html code used in this application, you will notice that in order to create this simple layout, I made use of the following html tags:

  • <form>
  • <input>
  • <div>
  • <button>

I used these four html tags to make up the structure of the document and some css to make it look a little more presentable.

I didn’t go crazy here with my CSS code so that we can focus on what is going on with our JavaScript code.

More Details about the html used for the App

I want you to pay attention to this snippet of html code below; it is probably the most important piece of our html code.

<form>
<input />
<button type="submit" id="add">Add to List</button>
</form>

Notice that we have a <form> element with an <input/> and a <button> . We will be using Javascript to take whatever the user enters in and adding it to the box that will house our list items.

That box is made with the following html code:

<div id="list">
<ul>
<!-- To do list items will be added here with JavaScript-->
</ul>
</div>

In the box the <ul> element is empty; it is empty because we will be using JavaScript to take what is entered in from the <input/> and creating <li> elements with it.

Now let’s finally take a look at the JavaScript code used for this app.

More Details on the JavaScript code used for the App

Below is the entire JavaScript script used for the Simple To Do List.

const form = document.querySelector("form")
const addButton = document.querySelector("button#add");
const clearButton = document.querySelector("button#clear");
const userInput = document.querySelector("input");
const list = document.querySelector("ul");
function createListItem(task) {
const li = document.createElement("li");
li.innerText = userInput.value;
//adds a strikethrough on click of li
li.addEventListener("click", () => {
strikeThrough(li);
});
list.append(li);
}
function clearList() {
const ul = list;
const arrayOfLi = Array.from(ul.children);
arrayOfLi.forEach((li) => li.remove());
}
//function for when list item has been complete
function strikeThrough(li) {
li.className = "strike-through";
}
//event listener to add to list
form.addEventListener("submit", (event) => {
event.preventDefault();
createListItem(userInput);
});
//event listener to clear out listclearButton.addEventListener("click", clearList);

At the top of the script, I have defined the following variables: form, addButton, clearButton, userInput and list . These variables have actual html code from our document saved inside them!

This is made possible by the DOM; the DOM gives us access to a method called document.querySelector() which is used to search for different things that exist in the html document. As a result of the DOM converting the html used into a collection of objects(nodes), we are able to use the html code that we get from the given method in the same way that we would use the JavaScript data types that we are familiar with.

But there is one thing you should be careful with…

The DOM gives us access to some methods that return back two data types that are not native to JavaScript. These two data types are the HTML Collection and the Nodelist.

Both of these data types are used to store a collection of html nodes, so they are pretty similar to the arrays that JavaScript has but there are some key differences.

HTML Collection vs. Nodelists

Both of these data types are used to store a collection of html nodes but they are different in what methods are available to each of them.

HTML Collections and Nodelists both do not have access to popular array methods such as .map() or .filter(). What that means is that if we would like to iterate over them, we are limited in our options of what we can do.

With that being said, nodelists are much easier to work with than html collections because nodelists have access to the .forEach() which will make iteration a little easier.

If we wanted to only use html collections, we would have to use a for loop or a while loop to iterate over them, so for the sake of abstraction, try to always use methods that return nodelists if you can.

But there is a way in which we can turn them both to arrays if we want.

There is a method called Array.from() that we can use convert any html collection or nodelist to an array. According to w3Schools, the Array.from() method returns an Array object from any object with a length property or an iterable object.

We can use this method to convert nodelists and html collections because they are both iterable objects with a length property. I have used this method in some of my JavaScript code so I’ll be sure to point it out to you.

While this method is very powerful, be careful if you use it because it is not supported in older browsers.

Now Let’s take a look at some of the functions in our script.

A Closer Look at Our Functions

We have the following three functions in our script file:

  1. createListItem()
  2. strikeThrough()
  3. clearList()

Our first function is used to convert a user’s input to an <li> element to be inserted into the <ul> element of the box from our html. Here is the code for createListItem() below so you don’t have to keep scrolling up to see it.

function createListItem(task) {
const li = document.createElement("li");
li.innerText = userInput.value;
//adds a strikethrough on click of li
li.addEventListener("click", () => {
strikeThrough(li);
});
list.append(li);
}

As we can see the function has a parameter called task ; task just represents the user input that we have stored into a variable that we made at the top of our script called userInput .

We use a method called document.createElement() and pass in the element we want to create as a string. After storing that newly created <li> element into a variable we call the property .innerText on it so that we can store some text inside.

Remember that I said earlier that JavaScript can interact with the html as if it is an object, so that means that the object has access to various keys (or in this case properties). innerText is one of the properties that the DOM gives us access to when the html is converted to a node. We use .innerText on theli to store the value of the user’s input inside of it.

Then we call the .addEventlistener() method on the our li variable.

Event Listener’s are one of the most important things that the DOM gives to us and it is something that you will always be making use of as a Fron-end Developer.

What is an Event Listener?

In JavaScript, an event, is something that happens when a user interacts with a website or application in some way. A good example of an event we are all familiar with would be a “click” event. A click event happens when a user clicks something.

To help illustrate the point to you, think of popular social media websites such as FaceBook or Instagram. Tthere are many events happening all throughout these websites. So what we can do is tell JavaScript to “listen” for an event. When that event happens, we can give JavaScript some code to execute in response to that event.

So if we go back to our createListItems() function, we have told JavaScript that when someone clicks on an li tag, execute another function called strikeThrough(li). strikeThrough() is a function that takes in an li tag created by the DOM and creates a line through it.

In order to understand what this function is doing, I would like you to go back up to the codepen that I embedded above and create a list item and then click that list item. You should see a line cross through the list item. I managed to accomplish that by using the .className property given to us by the DOM as well as some css code that I wrote.

If you’re interested in learning more about how I did this, please feel free to more closely examine the css code that I wrote.

Clearing Out Our To Do List

In order to clear out our to do list we have created a function called clearList(). This function lets us make use of a DOM method called .remove() which we can call on html nodes to remove them from the page.

The code for this function is provided below:

function clearList() {
const arrayOfLi = Array.from(list.children);
arrayOfLi.forEach((li) => li.remove());
}

This method is the place where we finally make use of the Array.from() method that I told you about earlier.

In this function, we have a variable called arrayOfLi and this variable is going to store all of our the <li> elements that we have created in our To Do List App. Notice that inside of arrayOfLi we store the result of called Array.from() on list.children. At the top of our script, we created a variable called list and we used .querySelector() to store find the <ul> element in our app and store it.

Once stored we can call .children on the <ul> element which will return an html collection of all the nodes nested inside the <ul> which will be a collection of <li> elements. Now we use Array.from() to convert that html collection into a regular JavaScript Array.

Once we have an array we can then use the array method .forEach() to iterate over each nested <li> element and remove it from our web page.

One More Thing About Our Event Listeners

Let’s wrap up the two snippets of code from our script

//event listener to add to list
form.addEventListener("submit", (event) => {
event.preventDefault();
createListItem(userInput);
});
//event listener to clear out listclearButton.addEventListener("click", clearList);

Here we add one event listener to the form in our html and to the “clear list button”. Both of these event listeners allow us to execute some code when a certain event is triggered by the user.

Let’s take a closer look at the event listener on the form. Instead of passing a premade function to the second argument of the event listener we create our own function with event as a parameter. event is a parameter that anticipates an event object to be passed to it as an argument when the event listener is triggered. The event object passed to the function in the second argument is dependent on the type of event we specify on the event listener in its first argument.

We used a “submit” event for this event listener instead of a “click” event like we used for the other event listeners. We can use the “submit” event here because the form variable has the <form> element from our html document stored inside it.

Whenever a form is submitted on a web page, the default event is to send a POST request to a server of some kind.

The problem with this is that we are not making use of a backend in our app so we have no server to submit the form.

We can use event.preventDefault() to stop the form from taking it’s default action when the submit button is pressed. The “submit button” in this case is our “Add to List Button” because if we look ath the html code for this app, that button has a type attribute with a value of “submit” on it.

Wow…that was a lot of stuff to go through

But hopefully you got to the end of this project with me.

Now it is Your Turn

The best way to get the best use out of any code tutorial is to make it your own in some way. One thing you can do to make this app your own would be to add some additional feature onto it with the DOM.

Below I will provide some resources you can use to do just that…

Please let me know if you liked this post by liking it or commenting on it

Stay tuned, I will be coming out with more programming tutorials and posts.

Resources

W3 School’s Documentation on Event Listeners

--

--

Patrick Pierre
Patrick Pierre

Written by Patrick Pierre

I am a Software Developer who is passionate about contributing to the tech industry. Connect with me on https://twitter.com/Pierre_WebDev

Responses (1)