6.3. Basics of JavaScript: Working with HTML/DOM Elements and Arrays

 

Interacting with HTML/DOM Elements

Now we've come to one of the most interesting topics, and you'll fully experience the benefits and power of JavaScript when working with web pages. As you know, a web page consists of various elements, known as HTML tags. Additionally, various CSS classes are assigned to these elements to change their styles, such as color, text font, border, and more. All these elements form a specific structure that is described using the Document Object Model (DOM).

The DOM, or Document Object Model, in a web browser is a programmatic representation of a web page or document in the form of a hierarchical structure of objects that can be controlled and manipulated using JavaScript. The DOM is a tree-like structure in which each HTML element, such as headers, paragraphs, images, forms, and others, is represented as an object, element attributes as object properties, and content as text or child elements.

The DOM allows web developers to dynamically change the content, structure, and styles of a web page without the need to reload the page. This makes user interactions more interactive and enhances the user experience.

JavaScript is used to access and manipulate DOM elements. Developers can create, modify, delete elements, change their attributes and styles, and respond to events such as mouse clicks and keypresses. Access to elements is achieved through specific parameters, such as tag name, CSS class, and identifier. There are several methods (functions) for this purpose:

getElementById  - Obtains an element by its ID.

getElementsByClassName - Retrieves all elements with a given CSS class name.

getElementsByTagName - Retrieves all elements by a specific HTML tag.

querySelector - A universal method to obtain a single element using any element attribute (class, ID, tag, and others).

querySelectorAll - A universal method to obtain all elements using any element attribute (class, ID, tag, and others).

Here are examples of using these functions:

// Getting an element by IDlet headerElement = document.getElementById("header");let headerElement = document.querySelector("#header");
// Getting elements by classlet buttons = document.getElementsByClassName("button");let buttons = document.querySelectorAll(".button");
// Getting elements by taglet tables = document.getElementsByTagName("table");let tables = document.querySelectorAll("table");

 In almost all cases, these functions are used with the document object, so remember this.

Now that we have obtained the necessary elements, we can change their properties and parameters. 

Changing Styles:

You can change the styles of elements using the style property. For example, to change the background color of an element:

headerElement.style.backgroundColor = "blue";

 Changing Content:

To change the text content of an element, you can use the textContent property:

headerElement.textContent = "Hello, world!";

 Getting Element Values:

All HTML elements can have certain attributes and properties. Sometimes you need to know their values. Since there are many properties and attributes, it's impossible to memorize them all. Therefore, a simple method is used. After you obtain an element or a group of elements, display the variable's value in the console using the console.dir() function:

Output of DOM element in browser console

Properties of DOM element displayed in console

The result will be displayed in the form of a tree. In the image above, the properties of the Input element were displayed, in which the user can enter values for further processing. Access to specific properties is achieved using a dot (.), for example:

let value = element.value; // The value entered in the input field of the elementlet height = element.style.height; // The height value of the elementlet id = element.id; // The assigned ID of the element

Exercise 1: Below is a code snippet that allows you to change the properties of a rectangle (color, size, and text inside) when buttons are pressed. Complete the code in the highlighted areas to implement the described functionality.

 

See the Pen Change Style Options_EN by Easy-Network Easy-Network (@Easy-Network-Easy-Network) on CodePen.

 

Arrays

An array in JavaScript is a special data structure that allows you to store multiple values (numbers, strings, objects, and so on) under one common name. Arrays are very useful when you need to store a lot of information and work with it.

How to create an array?

You can create an array using square brackets []:          

let numbers = [1, 2, 3, 4, 5];

In this example, numbers is an array that contains five numbers.                

How to access array elements?

Array elements are numbered starting from zero. That is, the first element is 0, the second is 1, and so on. You can access an array element by specifying its index in square brackets:

console.log(numbers[0]); // Outputs 1console.log(numbers[2]); // Outputs 3

How to add an element to an array?

You can add a new element to an array using the push() method. Here's how it's done:

numbers.push(6);

Now the array contains 6 elements, and the last one is 6.

How to remove an element from an array?

To remove an element from an array, you can use the pop() method. This method removes the last element from the array:

numbers.pop();

Now the array contains 5 elements, and the last element (number 6) has been removed.

Why is this useful?

Arrays are useful when you need to store a lot of data and manipulate it. For example, you can use arrays to store a list of products in an online store, game scores in the form of an array of scores, or even to store and process data from forms on websites.

Example: Working with an array

let fruits = ['apple', 'banana', 'orange'];
// Display the number of elements in the arrayconsole.log(fruits.length); // Outputs 3
// Add a new fruitfruits.push('pear');
// Display all fruits in the arrayfor (let i = 0; i < fruits.length; i++) {  console.log(fruits[i]);}

In this example, we created an array called fruits, added a new fruit to it, and displayed all the fruits using a loop.

Exercise 2: Given an array numbers, create a function findMax that takes the array and finds the maximum number, returning it to the function displayNumber that takes the found number and displays it in a specified rectangle. The entire operation starts with pressing the "Start" button.

 

See the Pen Task 2. Array_EN by Easy-Network Easy-Network (@Easy-Network-Easy-Network) on CodePen.