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:

For example:

var name = \\\"Alice\\\"; // Using var to declare a variablelet age = 30; // Using let to declare a variableconst city = \\\"London\\\"; // Using const to declare a constant

Types of Variables

In JavaScript, there are several different data types:

Using Variables

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

console.log(name); // Outputs: Aliceconsole.log(\\\"Age: \\\"   age); // Outputs: Age: 30console.log(city   \\\" is a beautiful city\\\"); // Outputs: London is a beautiful city

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

\\\"Mastering

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 IDlet elementsByClassName = document.getElementsByClassName(\\\"className\\\"); // Access a collection of elements by class namelet 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

Adding and Removing Elements

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

For example:

// Create a new elementlet newElement = document.createElement(\\\"div\\\");newElement.textContent = \\\"Hello, world!\\\";document.body.appendChild(newElement); // Add the new element to the document bodydocument.body.removeChild(newElement); // Remove the element from the document body

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

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?

","image":"http://www.luping.net/uploads/20241022/17296059666717b14edad29.png","datePublished":"2024-11-02T14:40:20+08:00","dateModified":"2024-11-02T14:40:20+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Mastering JavaScript and DOM Manipulation

Mastering JavaScript and DOM Manipulation

Published on 2024-11-02
Browse:211

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

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


  
    EconoMe

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
Release Statement This article is reproduced at: https://dev.to/labex/mastering-javascript-and-dom-manipulation-3e3e?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3