Today topic:
1- Arrays
2-Document Object Model (DOM):
Objects and Collections
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 1
10
JavaScript: Arrays
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 2
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 3
10.1 Introduction
Arrays:
Data structures consisting of related data items
JavaScript arrays
“dynamic” entities that can change size after they are
created
An array is a group of memory locations
All have the same name and normally are of the same
type (although this attribute is not required in
JavaScript)
Each individual location is called an element
We may refer to any one of these elements by
giving the array’s name followed by the position
number of the element in square brackets ([])
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 4
10.2 Arrays (Cont.)
The first element in every array is the zeroth element.
The ith element of array c is referred to as c[i-1].
Array names follow the same conventions as other
identifiers
A subscripted array name (Ex: myArray[i])
can be used on the left side of an assignment to place a new value
into an array element ex: myArray[i]=5
can be used on the right side of an assignment operation to use its
value Ex:n1=myArray[i]
Every array in JavaScript knows its own length, which
it stores in its length attribute and can be found with
the expression arrayname.length
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 5
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 6
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 7
10.3 Declaring and Allocating
Arrays
JavaScript arrays are Array objects.
You use the new operator to create an array
and to specify the number of elements in
an array.
The new operator creates an object as the
script executes by obtaining enough memory to
store an object of the type specified to the right
of new ©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 8
let's remember this example
©1992-2012 by Pearson Education, Inc. All
Rights Reserved.
©1992-2012 by Pearson Education, Inc. All
Rights Reserved.
10.4 Examples Using
Arrays
Zero-based counting is usually used to
iterate through arrays
JavaScript reallocates an Array when a
value is assigned to an element that is
outside the bounds of the original Array
var myArray = ["A", "B", "C"];
myArray[5] = "Z";
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 11
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 12
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 13
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 14
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 15
10.4 Examples Using Arrays
(Cont.)
Using an Initializer List
Arrays can be created using a comma-
separated initializer list enclosed in square
brackets ([]) Ex: var myArray = [10, 20, 30];
The array’s size is determined by the
number of values in the initializer list
The initial values of an array can be specified
as arguments in the parentheses following
new Array ex: var myArray=new Array(10, 20,
30);
The size of the array is determined by the
number Question?
of valuesnew
in Array(10)
parentheses
vs new Array[10]
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 16
10.4.2 Initializing Arrays with
Initializer Lists
The example in Figs. 10.5–10.6 creates
three Array objects to demonstrate
initializing arrays with initializer lists.
Figure 10.5 is nearly identical to Fig. 10.3
but provides three divs in its body element
for displaying this example’s arrays.
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 17
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 18
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 19
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 20
10.4.3 Summing the Elements
of an Array with for and for…in
JavaScript’s for…in Repetition Statement
Enables a script to perform a task for each element in an array
var numbers = [10, 20, 30, 40]; var numbers = [10, 20, 30, 40];
var sum = 0; var sum = 0;
for (var i = 0; i < numbers.length; i++) for (var index in numbers)
{ {
sum += numbers[i]; sum += numbers[index];
} }
document.writeln("Sum = " + sum); document.writeln("Sum = " + sum);
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 21
10.4.3 Summing the Elements
of an Array with for and for…in
The example in Figs. 10.7–10.8 sums an array’s
elements and displays the results.
The document in Fig. 10.7 shows the results of the
script in Fig. 10.8.
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 22
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 23
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 24
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 25
10.5 Random Image Generator
Using Arrays
In Chapter 9, the random image generator
required image files to be named with the word
die followed by a number from 1 to 6 and the file
extension .png (e.g, die1.png).
The example in Figs. 10.11–10.12 does not
require the image filenames to contain integers in
sequence.
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 26
10.5 Random Image Generator
Using Arrays
It uses an array pictures to store the
names of the image files as strings.
Each time you click the image in the document,
the script generates a random integer and uses
it as an index into the pictures array.
The script updates the img element’s src
attribute with the image filename at the
randomly selected position in the pictures
array.
We update the alt attribute with an appropriate
description of the image from the descriptions
array.
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 27
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 28
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 29
30
12
Document Object Model (DOM):
Objects and Collections
©1992-2012 by Pearson Education, Inc.
All Rights Reserved. 31
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 32
12.1 Introduction
The Document Object Model (DOM) gives you
scripting access to all the elements on a web
page.
getElementById method
Returns objects called DOM nodes
Every piece of an HTML5 page (elements,
attributes, text, etc.) is modeled in the web
browser by a DOM node
©1992-2012 by Pearson Education, Inc.
All Rights Reserved. 33
12.3 Traversing and Modifying a
DOM Tree (Cont.)
The DOM element methods setAttribute
and getAttribute allow you to modify an
attribute value and get an attribute value,
respectively.
©1992-2012 by Pearson Education, Inc.
All Rights Reserved. 34
12.5 Dynamic Styles
An element’s style can be changed
dynamically
E.g., in response to user events
Can create mouse-hover effects, interactive menus and
animations
The document object’s body property
Refers to the body element
The setAttribute method is used to set the style
attribute with the user-specified color for the
background-color CSS property.
If you have predefined CSS style classes defined for
your document, you can also use the setAttribute
method to set the class attribute.
©1992-2012 by Pearson Education, Inc.
All Rights Reserved. 35
©1992-2012 by Pearson Education, Inc. All
Rights Reserved. 36
Another way to modify a DOM
attribute
In addition to setAttribute and getAttribute
methods,
element.setAttribute("attribute", "value");
element.getAttribute("attribute");
The value of an HTML attribute can be also set
and get using element.attribute = value;
Ex1: document.body.style.backgroundColor=inputColor
Ex2: document.body.setAttribute("style", "background-color: " +
inputColor);
Note: CSS property with hypen
When a CSS property have a hyphen, it is
removed and the first letter after the
hyphen is capitalized
Ex:
background-color
backgroundColor
visibility and display properties
Can be both used to hide or show an element
show
object.style.visibility =“visible”
object.style.display=value //value can be “inline”,
“block”,..
Hide
object.style.visibility=“hidden”
object.style.display=“none”
Difference:
Visibility “hidden” keep the element in its
position but hidden.
Display “none” removes the entire element.
Regular Expression
The string method match() is used to match a
regular expression.
In the format /pattern/modifier,
string.match(/pattern/modifier);
Where modifier can be (i) to perform case
insensitive, (g) to find all matches, and (m) for
multiline matching str.match(/^[A-Za-z]+$/i);
str.match(/^[A-Z]+$/i);
Ex: str.match(/^hello/i);
var str = "HelloWorld";
var result = str.match(/^[A-Za-z]+$/);
document.writeln(result); // ["HelloWorld"]
Ex: form validation using
javascript
Validate form fields before sending to
server.
Use the form element onsubmit event.
Use regular expression to check that form
fields meat the requirement.
Validate the following
Name: only letters.
postcode: numbers, 5 only.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
</head>
<body>
<form onsubmit="return validateForm()" method="post">
<label for="name">Name (only letters):</label>
<input type="text" id="name" name="name">
<br><br>
<label for="postcode">Postcode (5 digits only):</label>
<input type="text" id="postcode" name="postcode">
<br><br>
<input type="submit" value="Submit">
</form>
©1992-2012 by Pearson Education, Inc.
All Rights Reserved.
<script>
function validateForm() {
// Get the values of the form fields
var name = document.getElementById("name").value;
var postcode = document.getElementById("postcode").value;
var namePattern = /^[A-Za-z]+$/; // Regular expression for Name: only letters
var postcodePattern = /^\d{5}$/; // Regular expression for Postcode: 5 digits only
// Validate Name
if (!namePattern.test(name)) {
window.alert("Name must contain only letters.");
return false; // Prevent form submission
}
// Validate Postcode
if (!postcodePattern.test(postcode)) {
window.alert("Postcode must be 5 digits.");
return false; // Prevent form submission
}
return true; // If both validations pass, allow the form to be submitted
}
</script> </body> </html>
©1992-2012 by Pearson Education, Inc.
All Rights Reserved.
refrences
http://www.w3schools.com