MY JOURNEY LEARNING JAVASCRIPT(WEEK 3: DOM(Document Object Model)

Minolta Ndlovu
5 min readMar 8, 2021

In my first article, I mentioned that one of the most important JavaScript functions is to add dynamic features to web pages. In this article, I will breakdown how JavaScript manipulates HTML elements to add these dynamic features by introducing DOM(Document Object Model).

Photo by Florian Olivo on Unsplash

WHAT IS DOM?

DOM is a programming interface for HTML. It defines HTML documents as standard objects that can be accessed and modified by scripting languages like JavaScript. To better understand this concept, let’s first define an object.

What is an object?

An object is an abstract data type that has state(properties) and behavior(methods). In real life, a car is an object. A car has properties like color and size, as well as methods like start and stop. Although all cars have the same properties these properties hold different values. Some cars are red and others are black or green or yellow just to mention a few colors. Cars also have the same basic functionalities (methods) which are called at different times and some cars may have additional functionalities on top of the basic ones. In programming, we also create objects that group related concepts in a hierarchy that is represented in a tree structure. The root of the tree is the name of the object, and the tree branches are all the data fields (properties) stored by this object. Below is a visualization of our car object:

HTML Documents

Just like objects, elements in HTML documents are structured in a hierarchy.

<html> 
<head>
<title>My Blog</title>
</head>
<body>
<h1 class="heading"> Welcome to my Blog!<h1>
</body>
</html>

The hierarchal structure of HTML elements makes it easy for programming languages to access and modify elements, and for humans to glide through the document. However, it is important to note that HTML documents are still not objects. They need to be translated to objects before programming languages can connect to the HTML page. This is where DOM comes in.

The DOM represents the whole HTML document as a single object, making it easy for programming languages to access and manipulate ids, classes, attributes, or elements using methods provided by the Document object.

Below is a visualization of how DOM would represent an HTML document as an object:

DOM AND JAVASCRIPT

const headingEl = document.querySelector(".heading").textContent;
console.log(headingEL);
//OUTPUT:
// Welcome to my Blog!

In the above code, JavaScript selects an HTML element using the element’s class name and outputs the text content on the console. The DOM interface contains properties and methods that JavaScript uses to:

  • change all elements
  • change all attributes
  • change all CSS styles
  • remove existing elements and attributes
  • add new elements and attributes
  • react to HTML events specified in the page, for example, a button click
  • create new events on the web page

DOM HTML METHODS

<html> 
<head>
<title>My Blog</title>
</head>
<body>
<h1 class="heading"> Welcome to my Personal Website!<h1>
<section id="about-me">
<h2>ABOUT ME</h2>
<p> I am a front-end development enthusiast </p>
<p> I am a self-taught web developer </p
</section>
</body>
</html>

All the methods that we will use in the next sections will be pointing to the HTML document above.

Methods for accessing HTML elements

  1. getElementById : returns an HTML element with the given id.
const aboutEl = document.getElementById("about-me");

2. getElementByTagName: returns a live HTMLCollection ( array-like object) of all child elements with the given tag name. The list is live because it updates itself automatically as the HTML document changes. The elements, like in an array, can be accessed using index numbers.

const pTag = document.getElementByTagName("p");

3. getElementbyClassName: returns a live array-like object of all child elements with the given class name.

const classEl = document.getElementByClassName("heading");

4. querySelector: returns the first element in the document that matches the specified selector(s).

//get the first <p> tag element
const tagSel = document.querySelector("p");
//get the first element with class="heading"
const classSel = document.querySelector(".heading");
//get the first element with id="about-me"
const idSel = document.querySelector("#about-me");

Methods for changing HTML elements

  1. element.innerHTML : sets or returns the HTML content of the selected element.
console.log(aboutEL.innerHTML);//OUTPUT
<h2>ABOUT ME</h2>
<p> I am a front-end development enthusiast </p>
<p> I am a self-taught web developer </p>
//You can assign a new value for the innerHTML using
aboutEL.HTML = new inner HTML value

2. element.setAttribute (attribute, value): changes the attribute value of an HTML element. If the attribute already exists, the value is updated.

document.getElementByTagName("h2")[0].setAttribute("class", "about-header"); //this adds a class on the first h2 element:
//<h2 class="about-header">ABOUT ME</h2>

3.element.style.property : change the style of an HTML element

pTag[0].style.color = pink;//changes the color of the text 

Adding Event Handlers

JavaScript can handle events that occur when a user or the browser operates on a web page. When a page loads, an event is created. Similarly, when a user clicks a button, an event is created. JavaScript allows developers to execute code when an event is detected. In this article, I will focus on the onClick event type.

HTML allows programmers to add event handler attributes to HTML elements.

<html>
<body>
<button onclick="myFunction()"> click me! </button>
<p class="demo"></p>
</body>
<html>

The above HTML code displays a button, click me!

function myFunction() {
document.getElementByClassName("demo")[0].textContent = "You
clicked a button!";
}

When a user clicks on the button, the function, myFunction gets called and the text, you clicked a button! is displayed on the web page. This is a simple example illustrating how JavaScript handles events.

There are a lot more methods provided by the Document object but my article will end here. Stay tuned for more!

--

--