A simple guide to handle HTML in JavaScript

Subscribe to my newsletter and never miss my upcoming articles

Perhaps after some time writing your HTML and style codes, you realized that it would be necessary to programmatically control some changes in the layout and appearance of your application, in addition to some actions that would respond to user interactions with your page.

In this article, I am going to explain what is the DOM, how to access it, how to change it, and even how to know when a user interacts with HTML elements handling click, hover, and other events - and we will do it all with JavaScript.

So, let's start with the basics.

What is DOM?

MDN web docs define it like this:

The DOM is a document model loaded in the browser and representing the document as a node tree, where each node represents part of the document (e.g. an element, text string, or comment).

This basically means that you can view the DOM as your app's HTML tree. Every time you add, remove or change some code in the HTML, it updates too.

But how can I access the DOM with JavaScript and change what I want to change there?

Man with doubts

One more thing before we go deep

Before you start learning how to read and edit elements, it is very important to understand what tags, IDs, and classes represent in HTML. If you are already an expert on this topic, go to the next one; otherwise, pay attention:

  • Tag: That's how we identify the type of elements that we create in HTML. The DOM may contain multiple elements with the same tag. Some commonly used are:
    • <div></div> -> represents a division
    • <p></p> -> represents a paragraph
    • <img /> -> represents an image
  • ID: Attribute that we can put in an element for making it unique. This way, we're able to directly refer to it in the styles and JavaScript code. Example:
    • <p id="my-paragraph"></p> -> we can't create another element with the same ID
  • Class: Allows us to identify multiple elements in the DOM, independent of their tags, or if they already have an ID. Example:
    •  <div class="rounded-box"></div>
       <div class="rounded-box"></div>
       <div class="rounded-box" id="my-unique-box"></div>
      

Now that you know the basics, we are ready to play some JavaScript code.

Accessing the DOM

JavaScript comes with a native object called document. It represents the complete content of the page. In other words, document gives us access to the whole DOM of an HTML page. Try printing it at the console:

console.log(document);

It works fine. But in most cases, we want to access a single element or its children. How to do it?

There is a lot of ways to get elements from the DOM. Let's see how to use the main approaches.

Getting an element by its ID

If we intend to obtain a single element using its ID, we can access it through the document object, looking for a child in it that has an ID corresponding to what we are looking for:

const boxElement = document.getElementById("my-unique-box");

Getting elements by their class name

When we want to get all the elements that share a class name, we use the following method:

const roundedBoxesList = document.getElementsByClassName("rounded-box");

We can iterate the given list or select a single element by its index on it:

// Iterate the list
for (let box of roundedBoxesList) {
  console.log(box);
}

// Get the first element from our list
const firstBox = roundedBoxesList[0];

Getting elements by their tag name

Let's suppose that we want to get all the paragraphs from an element, in this case, the document object. The following code does exactly what we need:

const paragraphsList = document.getElementsByTagName("p");

It works like the method we use to get elements from a class. Therefore, paragraphsList can be iterated too, and we are also able to select an element by its index in the list.

Using querySelector and querySelectorAll

querySelector allows us to find any type of element, but it will always return the first one that matches our query. It has the following syntax:

// get the first paragraph from the document
const paragraph = document.querySelector("p");
 // get the element by its id ("my-element")
const myElement = document.querySelector("#my-element"); 
 // get the first element from the given class name ("rounded-box")
const roundedBox = document.querySelector(".rounded-box");

querySelectorAll has the same syntax. But it returns all the elements that match our query.

Cool! But what can I do with an element?

Woman saying "Now I'm intrigued"

Well, we can read and change its attributes, content, children, and style and even delete it.

Attributes

In the example below, we modify its ID and add a new CSS class to the element:

boxElement.id = "another-id";
boxElement.classList.add("another-class");

Content

Do we need to rewrite its content? No problem:

boxElement.innerHTML = '<p id="my-paragraph">I am the contents of the box element now!</p>';

Children

We can also search for other elements inside it:

const myParagraph = boxElement.getElementById("my-paragraph");

If you want a complete list with all its children, just read their corresponding property on the element:

const boxChildren = boxElement.children; // An HTMLCollection (a list) with the children of boxElement

Style

A funny part of working with elements in JavaScript is changing their styles:

myParagraph.style.fontSize = "12";
myParagraph.style.color = "#111111";
myParagraph.style.backgroundColor = "#f0f0f0";

To learn more about the element's properties and methods, I strongly recommend that you consult the MDN docs about it.

Handling events

Sometimes we need to know when the user clicks on an element or does something else. Fortunately, we can prepare our code to handle those situations by using event listeners.

Let's suppose that in our HTML we have an attractive button:

<button>Click me!</button>

And we want to know when the user clicks on it to make the code print the following message on the browser console:

You clicked the button N times!

How to do it?

First, we store the button element inside a variable or a constant, as follows:

const button = document.querySelector('button');

Now, we create a counter that will store the number of times the user clicked the button:

let counter = 0;

Finally, we add an event listener to the button, specify the event type and write a callback function for it:

button.addEventListener('click', () => {
  console.log(`You clicked the button ${counter++} times!`);
});

Try it in your browser! 😃

Conclusion

Now you know everything you need to know to access the DOM, change it, and even perform an action when something occurs!

Minions celebrating

If you think you might need this guide later, bookmark it.

My final tip is to keep learning more about it and improving your personal challenges to become a better developer every day. And if you need any help, remember that I am here! 😉

Buy me a coffee

No Comments Yet