search
HomeWeb Front-endJS TutorialMastering JavaScript and DOM Manipulation

Introduction

Mastering JavaScript and DOM Manipulation

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.

Mastering JavaScript and DOM Manipulation

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.</script>
  • 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.</script>

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.

Mastering JavaScript and DOM Manipulation

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


  
    <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>
  
  

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

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

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

Mastering JavaScript and DOM Manipulation

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

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");

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

New HTML content

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:

Mastering JavaScript and DOM Manipulation

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
  • 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 element.
  • The document.body.removeChild() method removes the element from the element.

Event Handling

Event listeners allow you to respond to user actions.

addEventListener("event", function () {});

such as clicks, hover, or key presses:

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

Mastering JavaScript and DOM Manipulation

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
});

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?

  • ? Learn the latest JavaScript Skill Trees
  • ? Read More JavaScript Tutorials
  • ? Join our Discord or tweet us @WeAreLabEx

The above is the detailed content of Mastering JavaScript and DOM Manipulation. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.