DEV Community

Cover image for Mastering JavaScript and DOM Manipulation
Labby for LabEx

Posted on

Mastering JavaScript and DOM Manipulation

Introduction

MindMap

In this Lab, you'll step into the world of web development through the eyes of Alex, a budding web developer tasked with creating a dynamic personal finance tracker. To build a user-friendly application that allows users to input and track their daily expenses and income. The goal is clear - to develop an interface that's both intuitive and engaging, ensuring users can easily manage their finances without any hassle. This project not only aims to simplify personal finance management but also to introduce you to the fundamental concepts of JavaScript and DOM manipulation.

We will be working through 5 labs to complete the EconoMe project.

Knowledge Points:

  • Variable declarations (let, const)
  • DOM manipulation basics (getting elements, modifying element content)
  • Event Listening (addEventListener)

Basic JavaScript

JavaScript is a simple, object-oriented, and event-driven language. It is downloaded from the server to the client and executed by the browser.

It can be used with HTML and the Web, and more broadly on servers, PCs, laptops, tablets, and smartphones.

Its characteristics include:

  • Typically used for writing client-side scripts.
  • Mainly used to add interactive behavior in HTML pages.
  • It is an interpreted language, executed as it is interpreted.

So, how do we include JavaScript in HTML?

The inclusion method is similar to CSS and can be done in three ways:

  • Directly in the HTML tags, for particularly short JavaScript code.
  • Using the <script> tag, JavaScript code can be embedded into the <head> and <body> of the HTML document.
  • Using an external JavaScript file, write the JavaScript script code in a file with a .js suffix and include it by setting the src attribute of the <script> tag.

For example, if we press F12, we can see that many external JavaScript files are included in this page, and by clicking on Event Listeners, we can observe that there are many types of events within the page.

Now, let's add the <script> tag to ~/project/index.html to include the script.js file.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>EconoMe</title>
    <link rel="stylesheet" href="./style.css" />
    <!-- Add the script tag to index.html -->
    <script src="./script.js"></script>
  </head>
  <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

Next, let's learn how to define variables in JavaScript!

What are Variables

Variables can be seen as containers for storing information. In programming, we use variables to store data values. JavaScript is a dynamically typed language, meaning you don't need to declare the type of a variable. The type will be determined automatically during the execution of the program.

Declaring Variables

In JavaScript, you can use the var, let, or const keywords to declare variables:

  • var: Before ES6, var was the primary way to declare variables, and it has function scope.
  • let: Introduced in ES6, let allows you to declare block-scoped local variables.
  • const: Also introduced in ES6, used to declare a constant that cannot be changed once declared.

For example:

var name = "Alice"; // Using var to declare a variable
let age = 30; // Using let to declare a variable
const city = "London"; // Using const to declare a constant
Enter fullscreen mode Exit fullscreen mode

Types of Variables

In JavaScript, there are several different data types:

  • String: Text data, like "Hello, World!".
  • Number: Integers or floating-point numbers, like 42 or 3.14.
  • Boolean: true or false.
  • Object: Can store multiple values or complex data structures.
  • null and undefined: Special types representing "no value" and "value not defined," respectively.

Using Variables

Once variables are declared, you can use them in your program:

console.log(name); // Outputs: Alice
console.log("Age: " + age); // Outputs: Age: 30
console.log(city + " is a beautiful city"); // Outputs: London is a beautiful city
Enter fullscreen mode Exit fullscreen mode

The console.log() static method outputs a message to the console.

DOM Manipulation

DOM (Document Object Model) is a cross-platform, language-independent interface that treats HTML and XML documents as a tree structure, where each node is a part of the document, such as elements, attributes, and text content.

Accessing DOM Elements

To manipulate the content of a web page, you first need to access the elements in the DOM tree. You can use various methods to access elements, such as by their ID, class name, or tag name:

let elementById = document.getElementById("elementId"); // Access element by ID
let elementsByClassName = document.getElementsByClassName("className"); // Access a collection of elements by class name
let elementsByTagName = document.getElementsByTagName("tagName"); // Access a collection of elements by tag name
Enter fullscreen mode Exit fullscreen mode

Add the following code to the ~/project/script.js file of the EconoMe project:

const form = document.getElementById("record-form");
const recordsList = document.getElementById("records-list");
const totalIncomeEl = document.getElementById("total-income");
const totalExpenseEl = document.getElementById("total-expense");
const balanceEl = document.getElementById("balance");
Enter fullscreen mode Exit fullscreen mode

Modifying Element Content

Once you have a reference to an element, you can modify its content. The innerHTML and textContent properties are commonly used for this purpose.

For example, to insert <p>New HTML content</p> into a div element with id=content and replace "Hello" with "New text content" in a span element with id=info, you would use the following JavaScript code:

Adding and Removing Elements

You can dynamically add or remove elements on the page using JavaScript.

For example:

// Create a new element
let newElement = document.createElement("div");
newElement.textContent = "Hello, world!";
document.body.appendChild(newElement); // Add the new element to the document body
document.body.removeChild(newElement); // Remove the element from the document body
Enter fullscreen mode Exit fullscreen mode
  • In an HTML document, the document.createElement() method creates the HTML element.
  • The document.body.appendChild() method adds the new element to the end of the <body> element.
  • The document.body.removeChild() method removes the element from the <body> element.

Event Handling

Event listeners allow you to respond to user actions.

addEventListener("event", function () {});
Enter fullscreen mode Exit fullscreen mode

such as clicks, hover, or key presses:

elementById.addEventListener("click", function () {
  console.log("Element was clicked!");
});
Enter fullscreen mode Exit fullscreen mode

After learning the basic DOM operations, you can add the following code to the ~/project/script.js file of the EconoMe project:

document.addEventListener("DOMContentLoaded", function () {
  const form = document.getElementById("record-form");
  const recordsList = document.getElementById("records-list");
  const totalIncomeEl = document.getElementById("total-income");
  const totalExpenseEl = document.getElementById("total-expense");
  const balanceEl = document.getElementById("balance");
  let draggedIndex = null; // Index of the dragged item
});
Enter fullscreen mode Exit fullscreen mode

The DOMContentLoaded event in JavaScript is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This makes it an important event for running JavaScript code as soon as the DOM is ready, ensuring that the script interacts with fully parsed HTML elements.

This lab does not require previewing the effect at this point. We will review it after completing the code in the following steps.

Summary

In this lab, you embarked on the journey of building a basic yet fundamental part of a personal finance tracker with Alex. You've set the stage for a dynamic web application by setting up the project environment and using JavaScript to manipulate the DOM, showing initial financial states. The key takeaway is understanding how JavaScript interacts with HTML elements to dynamically change the content of a web page, laying the groundwork for more interactive features in the following steps.

This hands-on approach not only solidifies your understanding of JavaScript and DOM manipulation but also simulates real-world web development scenarios, preparing you for more complex projects ahead.


πŸš€ Practice Now: Basic JavaScript and DOM


Want to Learn More?

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

You've missed Symbol and BigInt from the data types

Collapse
 
rafaeljohn9 profile image
JohnKagunda

Good starter's guide

Collapse
 
samuel_ogbaje_ff29fa7e57f profile image
Samuel Ogbaje

This is a good start for Dom manipulation

Collapse
 
code_passion profile image
CodePassion

Very Valuable information..