Array, HTML and JavaScript

Goals

Here we will learn about simple objects and one-dimensional arrays, as well as how to handle HTML elements from JavaScript.

  • Understand the concept of one dimensional arrays.
  • Understand how to use getElementsByTagName ()
  • Understand how to use  getElementById ()
  • Understand how to use getElementsByClassName ()
  • Understand how to use  operate DOM elements with JavaScript.
  • Understand the structure of values returned by getElementById (), getElementsByClassName (), etc.

Objects

An object is a collection of values. For example, an object called name is made of “first name” and “last name”.  An object called a position may be made up of “latitude” and “longitude”. Likewise, an object representing a person can be expressed as an object named “name”, along with their “first name”, “last name”, “age” and “sex”.

名前の構造

位置の構造

人の構造

Object Literal

In JavaScript, an object literal is used to express an object using actual values. An object literal has the following format.

{
Property Name: Value,
Property Name: Value,
...
}

A property name is a name given to each value existing in an object. For example, if you write a person’s name as an object literal, you can write something like this:

The value is enclosed in double quotes like “Keio” and “Taro”, because the value is a character string.

{
familyName: "Keio",
firstName: "Taro"
}

Property names can use arbitrary character strings, including spaces. If it contains spaces, it is necessary to enclose the property name in single quotes or double quotes. However, since there are restrictions on referring to objects that are to be reused later in the program, it is better to avoid using spaces or “-“. You may use kanji and hiragana, but it would be better to stick to roman characters.

{
familyName: "Keio",
firstName: "Taro"
}

Also, in the case of an object containing other objects like a person, it is possible to describe it as shown below. Here, pay close attention because the property “name” is drawn to the object “{familyName:” Keio “, firstName:” Taro “}}”.

{name: {familyName: "Keio", firstName: "Taro"}, age: 19, sex: "male"}

Object Declaration

It is easy to create variables containing objects. We will now look at creating an object that is initialized before the program is executed.

var variableName = {
propertyName: value, propertyName: value,
...
};

For example, if you want to create a human object you can do as follows.

var human = {
name: {familyName: "Keio", firstName: "Taro"},
age: 19, sex: "male"
};

Note: We have put in line breaks between the curly brackets {} so that the code is easier to read, but for practical purposes there is no need to have the contents of the object on different lines.

In JavaScript, there is another method of generating an object using the new operator. To create an object using the new operator, use a constructor. We will not go into details here, but the Date() object is one kind of object that uses the new operator. In a program using Date (), create an object as follows.

var date = new Date();

This uses a Date object which is an object provided by the system, creates a new object that has various functions that can be used, and assigns it to the variable date.

A function such as toLocaleString () (a function attached to an object is called a method) is defined as a member of the Date object beforehand, and these can be used through the variable date.

In other words, functions can be stored in the object and used using the object name. We will discuss this in greater detail later.

Referencing Objects

If you put an object into a variable, you must think about how you will use it. In order to refer to the value in the object in the program, it is written as follows:

variableName.propertyName;
variableName["propertyName"];
variableName['propertyName'];

Every row represents the same value, but if we use the first method to express the object, we must be careful. A problem arises if the property name is a number “123” or includes minus like “first-name” and does not conform to the naming convention of variable names. This is the main reason why it is better to not use strings such as blanks or minus as we mentioned before.

Also, in the above example of a human as an object, familyName is in the object name. We therefore have variable stored within other objects. We may refer to the properties as follows:

variableName.propertyName1.propertyName2;
variableName["propertyName1"]["propertyName2"];
variableName['propertyName1']["propertyName2"];

Specifically, the portion containing the value “Keio” is as follows.

human.name.firstName;
variableName["name"]["firstName"];
variableName['name']["firstName"];

With that said and done, how do you use these properties in an actual program? The following is an example of generating an object “human” and displaying the value of each property contained in the object. In this example, we use different expressions such as “human.name.familyName” ,”human.name [” firstName “]” to indicate that there are various  different expressions, but it is not possible to mix up expressions unnecessarily. Care must be taken to improve the readability of the program.

/* *
Object Creation
*/

var human = {
name: {familyName: "慶應", firstName: "太郎"},
age: 19, sex: "male" };

/* *
プロパティの表示
*/

alert("姓: " + human.name.familyName);
alert("名: " + human.name["firstName"]);
alert("年齢: " + human.age);
alert("性別: " + human['sex']);

 

One Dimensional Arrays

Many programming languages have a mechanism called an array to handle data of larger sizes. JavaScript is no exception. An array is one way to store multiple values within one variable name, followed by a number to reference each value.

配列

A place where each value in an array can be stored is called an “element”. As mentioned above, in the case of arrays, there is only one variable name for the whole array. The whole array is a collection of many elements. Each element can be used like the variables we learned about so far. We must also be careful to note that when referring to array elements and retrieving values, our style of declaration and referencing is different from ordinary variables.

Array Literal

Literals are determined for arrays as well. The array literals are as follows.

[value, value, value, ...]

The number of values is arbitrary, and it is possible to specify as many as 0 or more necessary numbers. In the case of 0, an empty array is generated.

This is how it looks with real data.

["佐藤", "鈴木", "田中", ...]

In the above example, all element values are character strings, but in JavaScript you can change the value type for each element. For example, if you write “[” a “, 3]”, the value of the first element is a character string, but the value of the second element is treated as a numeric value. Furthermore, it is also possible to create an array of objects, or to specify an array as one of the properties of the object.

Array Declaration

Even when declaring an array, there are many methods for generating an array initialized with an array literal as well as an object, and even a method using a constructor.

Here we will look at a method using array literals. The method using an array literal is simple and it is as follows:

var variableName = [value, value, value, ...];

In the following example, an array containing three character strings “” Sato “” “Suzuki” “” Tanaka “” is assigned to a variable named familyName.

var familyName = ["Sato", "Suzuki", "Tanaka"];

Also, to create an empty array (an array with no elements):

var familyName = [];

Array Manipulation

Various methods are prepared to perform operations on and manipulate array objects. Here are some of them.

Adding new elements to an array

Add element at the beginning (unshift)
var array = ['b', 'c'];
array.unshift('a');
alert(array); // ['a', 'b', 'c']
Add an element to the end (push)
var array = ['a', 'b'];
array.push('c');
alert(array); // ['a', 'b', 'c']

Combining elements of an array

Creating an array by combining two arrays (concat)
var array1 = ['a', 'b'];
var array2 = ['c', 'd'];

// New Array
var array = array1.concat(array2);

alert(array); // ['a', 'b', 'c', 'd']
alert(array1); // ['a', 'b']
alert(array2); // ['c', 'd']

Retrieving information from an array

Get the number of elements in an array (length)
var array = ['a', 'b', 'c'];
var len = array.length;
alert(len); // 3
Get the value of a specific element in an array (if the same element exists more than once then the first element) (indexOf)
var array = ['a', 'b', 'c'];
var index = array.indexOf('b');
alert(index); // 1
Get the position of the last occurrence of an element(lastindexOf)
var array = ['a', 'b', 'c'];
var index = array.lastIndexOf('c');
alert(index); // 2

Deleting elements in an array

Delete the first element (shift)
var array = ['a', 'b', 'c'];
array.shift();
alert(array); // ['b', 'c']
Delete the last element (pop)
var array = ['a', 'b', 'c'];
array.pop();
alert(array); // ['a', 'b']

Sort element contents alphabetically

var array = ["e", "c", "b", "a", "d"];
array.sort();
alert(array); // ["a", "b", "c", "d", "e"]

Referencing an array

Referencing an array is similar to referencing an object. Add a bracket after the variable name and specify a number within it. For example, to refer to the second element in the array named array, it is expressed as follows.

array[1];

The thing to notice here is that the array index starts at number 0. The first element of the array is at the 0th index, the second at the 1st index, the third at the 2nd index and so on.

You can also specify variables instead of numbers.  In the example below, an array is created on the first line, and 1 is assigned to the variable n at the third line. In the fourth line, the nth element counting each element of the array starting from 0 is displayed.

var array = ["Sato", "Suzuki", "Tanaka", "Watanabe", "Ito "Yamamoto"];
var n = 1;
alert(array[n]);//Suzuki

Also, by combining an array with a for statement, it is possible to output all the elements in order. In the example below, we use the length property to create a iteration with a for statement and display “The element at position n  of the array is: xx” for all the array elements.

var array = ["Sato", "Suzuki", "Tanaka", "Watanabe", "Ito "Yamamoto"];
var i;
for (i = 0; i < array.length; i++) {
alert("The element at position "+ i + "of the array is: " + array[i]);
}

Objects and Arrays

In fact, there are similarities in objects and arrays, as you can see from their representation methods. You can also refer to an object’s property with a “.” as you can with an array.

However, it is not possible to express “obj.0”, “obj.1”, “obj [0]”, “obj [1]” and so on, so be careful. In this case, it is necessary to express it as “obj [” 0 “]” “obj [” 1 “]”. A property is a string in an object, but in an array it is a number.

Linking HTML and JavaScript

Elements and Naming

In HTML, an ID and class can be attached to each element. By attaching IDs and classes, we are able to specify styles with CSS only for that element. Even in JavaScript, adding an ID or class makes it easier to specify the element.

id

The id attribute gives a unique ID (identifier) ​​for referring to an element. It is not possible to have the same ID in one document or webpage (that is, it must be unique).

The purpose of specifying the id attribute is to designate elements to be decorated with CSS and to perform processing by referring to specific elements in JavaScript.

This ID can be specified in a div element, a heading element or any other opening tag.

class

The class attribute specifies the class name for that element. Unlike the id attribute, the class attribute can use the same class name many times in one document. Also, it is possible to apply multiple classes to one element, separated by single-byte spaces.

Handling elements with JavaScript

When referring to an HTML element from JavaScript, it is necessary to first incorporate the element into a JavaScript program. Here, we will explain the connection between HTML elements using IDs and classes in JavaScript.

getElementById()

A getElementById () method is prepared in the document object as a function for linking HTML elements by specifying an ID from JavaScript. The getElementById () method takes an ID as an argument and returns an HTML element with that ID. By assigning a return value to a variable, it becomes easy to access that element from JavaScript.

HTML

...
<p id="p1234">テスト1</p>
テスト2

<button onclick="showContent();">Click Me</button>
...

JavaScript

function showContent() {
var ele = document.getElementById("p1234");
alert(ele.innerHTML);
}

テスト1

テスト2

In the above JavaScript, an element whose ID attribute is p1234 is assigned to a new variable ele. After that, HTML for the element whose ID is p1234, i.e. , all the HTML code written between the start tag with the specified ID and the end tag is stored in ele.

getElementsByClassName(“ClassName”)

getElementsByClassName () gets all the elements with the specified class attribute. In the example below, an element with a class attribute “aaa” is acquired. Here, there is a possibility that there are two or more elements having the class attribute “aaa” (in fact, in the example below, multiple elements have the class attribute “aaa”), and the return value is stored in an array.

HTML


Element 1

Element 2

Element 3

Element 4

Element 5

<button onclick="numOfaaa();">Click Me</button>

JavaScript

function numOfaaa() {

var classes = document.getElementsByClassName("aaa");

alert(classes.length);
}

Element 1

Element 2

Element 3

Element 4

Element 5

Multiple class names can also be specified simultaneously in JavaScript so that you can specify multiple class attributes in one tag. When specifying more than one, specify by separating with space as follows.

HTML


Element 1

Element 2

Element 3

Element 4

Element 5

<button onclick="numOfaaaacccc();>Click Me</button>

 

JavaScript

<="" p=""> function numOfaaaacccc() {
var classes = document.getElementsByClassName("aaaa cccc");

alert(classes.length);
}

 

Element 1

Element 2

Element 3

Element 4

Element 5


getElementsByTagName(“tagName”)

getElementsByTagName () is a method for specifying a tag name to obtain an HTML element. Like getElementsByClassName (), getElementsByTagName () also gets all the elements with the specified tag name and returns an array. In getElementsByTagName (), regardless of whether the id attribute or the class attribute is added, all items with the specified tag name are acquired.

HTML


Element 1

Element 2

Element 3

Element 4

Element 5

JavaScript

var pAll = document.getElementsByTagName("p");
alert(pAll.length);

 

DOM

The HTML document has a tree structure as described above. So, how do you show “where is the HTML document?” Use DOM to solve this problem. DOM is an abbreviation of Document Object Model, and is an arrangement for handling a document as an object. It seems difficult, but basically it is equivalent to the tree structure mentioned above. Let’s look at this in a little more detail.

See the figure below. This figure is a diagram in which the node “document” has a tree structure illustrating all its child elements, much like the tree structure we looked at before.

DOM

We introduced a function called document.getElementById () above. Actually, this is exactly the same interface as the DOM model itself. The meaning of this function is that it brings an element with the specified ID from the document document (the object at the top level of all HTML documents is the document in JavaScript). That is, the tree structure above is searched and the node with the specified ID is taken as the return value.

The object containing the element has various properties (values) that can be manipulated. For example, if you specify a property named firstChild for an element, you can get the first child element and you can get the second child element by specifying the property childNodes [1]. Here, the inside of the bracket is 1 because in JavaScript, the array starts at 0.

For example, an element containing the title “JavaScript” can be specified as follows:

 document.childNodes[1].firstChild.childNodes[1];

However, care should be taken because if there is a line break or an empty space between the tag and the tag in the HTML file, the newline or blank may be recognized as an element. It may be necessary to write it without including a line break as follows:

In addition, there are various properties other than firstChild and childNodes in the object storing the element. For example, in the property called innerHTML, the HTML code within the tree structure containing that element is obtained. An example of the property is shown below.

Property Explanation
attributes[] An array storing the attributes of a node
childNodes[] An array storing the child nodes of an element
firstChild The first child node of an element
innerHTML The HTML code present between the start and end tags of the element
innerText The text present between the start and end tags of the element
lastChild The last child node of an element
parentNode The parent node of the element
style The style attribute of the element that can be manipulated
value The value of the node

Exercise 5-1

Use prompt() is to input six names into an array, and create a program to display it with alert () three names at a time.

Exercise 5-2

Create a program to accept an input of five character strings using prompt () and display them one by one in alphabetical order by alert ().

Hint: You can use the sort () method.

Exercise 5-3

Create a program that creates a page that contains multiple p elements, counts the number of p elements using getElementsByTagName (), and displays that number with alert ().

Exercise 5-4

When you have the following HTML, create a button to change the contents of elements containing ccc, aaa and bbb.


Element 1

Element 2

Element 3

Element 4

Element 5

Element 1

Element 2

Element 3

Element 4

Element 5