DEV Community

Cover image for Adding Event Listeners and Understanding the DOM
pjparham
pjparham

Posted on

Adding Event Listeners and Understanding the DOM

What is the DOM?

MDN docs defines the DOM as the data representation of the objects that comprise the structure and content of a document on the web. In essence, it is the HTML that is actively being displayed on the web page. We can manipulate what is being displayed on the web page using various elements available in JavaScript by accessing the various nodes.

What is a node?

<body>
  <div>
    <p>First</p>
  </div>

  <div>
    <p>Second</p>
  </div>
</body>
Enter fullscreen mode Exit fullscreen mode

In the code snipit above, we have multiple nodes. Everything between the body tags is a node, the contents of an individual div element are a node, and the individual p tags are also nodes that can be accessed and manipulated.

Finding an element on the page

JavaScript has a few ways to find DOM nodes. Some of the methods that seem to get the most love are document.querySelector(), document.getElementById(), and document.getElementsByClassName(). Other available methods include document.getElementsByTagName() and document.querySelectorAll().

document.getElementById() in action
This method allows us to easily grab a node by grabbing it with the Id assigned to it.

Imagine we have the following code:

<div>
  <h1 id="heading">This is the heading</h1>
</div>
Enter fullscreen mode Exit fullscreen mode

In Javascript, we can access this element with the code document.getElementById('heading'). It is often helpful to assign this a variable, which I will demonstrate here:

const heading = document.getElementById('heading')
Enter fullscreen mode Exit fullscreen mode

the other methods in action
Given the following code, I will demo document.getElementsByClassName

  <div class="article-title">
    <p>3 ways to spice up your dining room</p>
  </div>

  <div class="article-title">
    <p>What trends to expect this fall</p>
  </div>

  <div class="article-title">
    <p>You won't believe what this celebrity said...</p>
  </div>
Enter fullscreen mode Exit fullscreen mode

Let's say you want to grab all of the elements at the same time, and even assign them to a variable name that can be more easily accessed. We can do that with the single line of code:

let articleTitles = document.getElementsByClassName('article-title')
Enter fullscreen mode Exit fullscreen mode

Debugging tip!

It is best practice to always console.log anytime you grab an element from the DOM. Some things can be tricky to grab, so it's always good to double check that the code is acting how you want it to before looking forward. Let's put all our previous code together to see that in action.
Our HTML at this point looks like:

<div>
  <h1 id="heading">This is the heading</h1>
</div>

<div class="article-title">
    <p>3 ways to spice up your dining room</p>
</div>

<div class="article-title">
    <p>What trends to expect this fall</p>
</div>

<div class="article-title">
    <p>You won't believe what this celebrity said...</p>
</div>
Enter fullscreen mode Exit fullscreen mode

While our JavaScript, with our newly added console.logs, looks like

const heading = document.getElementById('heading')
let articleTitles = document.getElementsByClassName('article-title')
console.log(heading)
console.log(articleTitles)!
Enter fullscreen mode Exit fullscreen mode

This is what would be expected in the console if everything is working correctly:
Console log of previous code

What is an event listener?

The addEventListener() method attaches an event handler to a specified element. addEventListener() expects two arguments: the type of event we want to listen for and a callback function that will be called whenever our event listener 'hears' what we tell it to listen for. Some of the most common types of event listeners used are click, mouseover, and keydown.

So now that we can grab nodes, how do we add event listeners to them?

It is most straightforward to add event listeners when we have assigned a variable name to an element we grabbed by its ID, so for this part of the article we will be focusing on the variable we previously named heading after getting the heading element by its ID. Since we have declared a constant variable for heading, the syntax will be heading.addEventListener(). But as previously mentioned, we must add the type of event we want to listen for and our callback function. For this demo we will be adding a click event listener to our page that simply displays a log in the console each time it is clicked.

heading.addEventListener('click', () => console.log('I was clicked!') )

Enter fullscreen mode Exit fullscreen mode

Our callback function is inside of the event listener as an arrow function. If we were to simply write heading.addEventListener('click', console.log('I was clicked!'), 'I was clicked!' would be in our console when we load the page, which would defeat the purpose of adding our event listener in the first place. If the event listener is added in properly, we should see the following in our console after we click our heading:
Console with our newly added console log produced from our event listener

Our console log is displaying as expected! As you explore adding event listeners in your code, you will find that you can add much more complicated functions as event listeners to create a highly interactive web page.

What about adding a function to our event listener?

If you want to put a function that you defined somewhere else in your code into an event listener, you simply leave out the () which calls the function from the event listener.

function sayHello(){
    console.log('Hello!')
};
heading.addEventListener("click", sayHello)
Enter fullscreen mode Exit fullscreen mode

Debug tip

I would encourage you to always put a console.log into event listeners when you first apply them to make sure it is responding how you want it to.

I hope this article helped demystify what the DOM is and how to add event listeners to your code to actively manipulate the DOM. Happy coding!

Top comments (0)