You are on page 1of 39

Java Script - DOM

Javascript object
Everything in JavaScript takes the form of an
object.
This means that it is a "package", which
contains various properties (pieces of
information) and methods (lists of instructions
that it can carry out).
DOM
• DOM - Document Object Model
• When a web page is loaded, the browser creates a
Document Object Model of the page.
• The W3C Document Object Model (DOM) is a
platform and language-neutral interface that allows
programs and scripts to dynamically access and
update the content, structure, and style of a
document.
• The HTML DOM model is constructed as a tree of
Objects:
• The Document Object Model (DOM) defines the logical
structure of documents and the way a document is accessed
and manipulated.
The HTML DOM is a standard object model and programming
interface for HTML.

It defines:
•The HTML elements as objects
•The properties of all HTML elements
•The methods to access all HTML elements
•The events for all HTML elements
The DOM Programming Interface

• The HTML DOM can be accessed with JavaScript


(and with other programming languages).
• In the DOM, all HTML elements are defined
as objects.
• The programming interface is the properties and
methods of each object.
• A property is a value that you can get or set (like
changing the content of an HTML element).
• A method is an action you can do (like add or
deleting an HTML element).
HTML DOM methods are actions you can perform (on
HTML Elements).
• HTML DOM properties are values (of HTML
Elements) that you can set or change.
•Eg: document.getElementById("demo").innerHTML =
"Hello World!";
getElementById is a method, while innerHTML is a
property
JavaScript Arrays
What is an Array

Arrays are complex variables that allow us to store more


than one value or a group of values under a single variable
name.

JavaScript arrays can store any valid value, including strings,


numbers, objects, functions, and even other arrays, thus
making it possible to create more complex data structures
such as an array of objects or an array of arrays.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Storing Single Values</title>
</head>
<body>
<script>
// Creating variables
var color1 = "Red";
var color2 = "Green";
var color3 = "Blue";
OUTPUT
// Printing variable values
document.write(color1 + "<br>");
document.write(color2 + "<br>"); Red
document.write(color3);
</script> Green
</body> Blue
</html>
Creating an Array
The simplest way to create an array in JavaScript is
enclosing a comma-separated list of values in square
brackets ([]), as shown in the following syntax:

var myArray = [element0, element1, ..., elementN];

Array can also be created using the Array() constructor as


shown in the following syntax. However, for the sake of
simplicity previous syntax is recommended.

var myArray = new Array(element0, element1, ...,


elementN);
<!DOCTYPE html>
<head>
<title>Creating Arrays in JavaScript</title>
</head>
<body>
<script>
// Creating variables
var colors = ["Red", "Green", "Blue"];
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ['J', "W", 32,44.55];

// Printing variable values


document.write(colors + "<br>");
OUTPUT
document.write(fruits + "<br>");
document.write(cities + "<br>");
document.write(person); Red,Green,Blue
</script> Apple,Banana,Mango,Orange,Papay
</body> London,Paris,New York
</html>
J,W,32,44.55
Accessing the Elements of an Array
 An array is an ordered collection of values. Each value in an
array is called an element, and each element has a numeric
position in an array, known as its index.
 Array elements can be accessed by their index using the square
bracket notation. An index is a number that represents an
element's position in an array.
 Array indexes are zero-based. This means that the first item of
an array is stored at index 0, not 1, the second item is stored at
index 1, and so on. Array indexes start at 0 and go up to the
number of elements minus 1. So, array of five elements would
have indexes from 0 to 4.
<!DOCTYPE html>
<head>
<title>JavaScript Access Individual Elements of an Array</title>
</head>
<body>
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits[0] + "<br>"); // Prints: Apple


document.write(fruits[1] + "<br>"); // Prints: Banana
document.write(fruits[2] + "<br>"); // Prints: Mango
document.write(fruits[fruits.length - 1]); // Prints: Papaya
</script>
</body>
</html>
Getting the Length of an Array
The length property returns the length of an array, which is the total number of
elements contained in the array. Array length is always greater than the index of
any of its element.

<!DOCTYPE html>
<head>
<title>JavaScript Get the Length of an Array</title>
</head>
<body>
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits.length); // 0utputs: 5
</script>
</body>
</html>
Looping Through Array Elements
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
for(var i = 0; i < fruits.length; i++)
{
document.write(fruits[i] + "<br>"); // Print array element
}
</script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
// Iterates over array elements
for(var fruit of fruits)
{
document.write(fruit + "<br>");
}
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
for(var i in fruits)
{
document.write(fruits[i] + "<br>");
}
Adding New Elements to an Array
<!DOCTYPE html>
<html lang="en"> To add a new element at the end of
<head> an array, use the push() method
</head> to add a new element at the
<body> beginning of an array use
<script> the unshift() method,
var colors = ["Red", "Green", "Blue"];
colors.push("Pink", "Voilet");
colors.unshift("Yellow", "Grey");
document.write(colors + "<br>");
document.write(colors.length);
</script> OUTPUT
</body>
</html> Yellow,Grey,Red,Green,Blue,Pink,Voilet
7
Removing Elements from an Array
To remove the last element from an array use the pop() method.

<html >
<head>
<title>JavaScript Remove the Last Element from an Array</title>
</head>
<body>
<script>
var colors = ["Red", "Green", "Blue"];
var last = colors.pop();
document.write(last + "<br>"); // Prints: Blue
document.write(colors.length); // Prints: 2
</script>
</body>
</html>
remove the first element from an array using the shift()
method
<html >
<head>
<title>JavaScript Remove the First Element from an
Array</title>
</head>
<body>
<script>
var colors = ["Red", "Green", "Blue"];
var first = colors.shift();

document.write(first + "<br>"); // Prints: Red


document.write(colors.length); // Prints: 2
</script>
</body>
</html>
Merging Two or More Arrays
<script>
var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];

// Creating new array by combining pets and wilds arrays


var animals = pets.concat(wilds);
<script>
var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];
var bugs = ["Ant", "Bee"];

// Creating new array by combining pets, wilds and bugs


arrays
var animals = pets.concat(wilds, bugs);
Creating a String from an Array
<script>
var colors = ["Red", "Green", "Blue"];

document.write(colors.join() + "<br>"); // Prints: Red,Green,Blue


document.write(colors.join("") + "<br>"); // Prints: RedGreenBlue
document.write(colors.join("-") + "<br>"); // Prints: Red-Green-Blue
document.write(colors.join(", ")); // Prints: Red, Green, Blue
</script>

<script>
var colors = ["Red", "Green", "Blue"];
document.write(colors.toString()); // Prints: Red,Green,Blue
</script>
Splicing and Slicing Arrays
 Adding or Removing Elements at Any Position

 The splice() method adds new items to an array.

 The slice() method slices out a piece of an array.


 The splice() method is mostly used when you need to delete
or add new elements to an array.
 The full syntax of the splice() method is as follows:
 Array_name.splice(start, removeCount, newItem,
newItem, newItem, ...)
 The splice() method needs at least one parameter, which is
the start index where the splice operation starts.
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
//Banana,Orange,Apple,Mango
fruits.splice(2);
document.getElementById("demo2").innerHTML = fruits; //Banana,Orange
</script>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

fruits.splice(2, 0, "Lemon", "Kiwi");


document.getElementById("demo2").innerHTML = fruits;
//Banana,Orange,Lemon,Kiwi,Apple,Mango
</script>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango","papaya"];
document.getElementById("demo1").innerHTML = fruits;

fruits.splice(2, 2, "Lemon", "Kiwi");


document.getElementById("demo2").innerHTML = fruits;
</script>
 The slice() method creates a new array.
 The slice() method does not remove any elements from the source array.
 The slice() method can take two arguments like slice(1, 3).
 The method then selects elements from the start argument, and up to (but
not including) the end argument.

<script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
var citrus = fruits.slice(1,3); //Banana,Orange,Lemon,Apple,Mango
document.getElementById("demo2").innerHTML = citrus; //Orange,Lemon
</script>
<script>
let languages = ["JavaScript", "Python", "C", "C++", "Java"];
let one = languages.slice();
document.getElementById("demo1").innerHTML = one;
let two = languages.slice(1, 4);
document.getElementById("demo2").innerHTML = two;
</script>
Sorting and reversing an array
 The sort() method sorts an array alphabetically
 The reverse() method reverses the elements in an array.

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo1").innerHTML = fruits.sort();

document.getElementById("demo2").innerHTML =

fruits.reverse();

</script>
Searching Through an Array

 If you want to search an array for a specific value,


you can simply use the indexOf() and lastIndexOf().
 If the value is found, both methods return an index
representing the array element.
 If the value is not found, -1 is returned.
 The indexOf() method returns the first one found,
whereas the lastIndexOf() returns the last one
found.
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange",
"Papaya"];

document.write(fruits.indexOf("Apple") + "<br>"); //
Prints: 0
document.write(fruits.indexOf("Banana") + "<br>");
// Prints: 1
document.write(fruits.indexOf("Pineapple"));
// Prints: -1
</script>
JavaScript Strings
JavaScript strings are for storing and manipulating text.

<script>
let one = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = one.length;

let text = "knowledge is \"power\"";


document.getElementById("demo1").innerHTML = text;
</script>

26
knowledge is "power"
JavaScript String Methods

There are 3 methods for extracting a part of a string:


 slice(start, end)
 substring(start, end)
 substr(start, length)
<p id="demo"></p>
<script>
let str = "AppleBananaKiwi";
document.getElementById("demo").innerHTML =
str.slice(7,13); //nanaKi
</script>

<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML =
str.slice(-12,-6);
</script>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML =
str.substr(7,3); //Ban
</script>

The difference is that the second parameter specifies


the length of the extracted part.
Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

A string is converted to lower case with toLowerCase():


<button onclick="myFunction1()">upper</button>

<p id="demo1">Hello students!</p>

<button onclick="myFunction2()">lower</button>

<p id="demo2">HELLO!</p>

<script>
function myFunction1() {
let text1 = document.getElementById("demo1").innerHTML;
document.getElementById("demo1").innerHTML =
text1.toUpperCase();
}
</script>
<script>
function myFunction2() {
let text2 = document.getElementById("demo2").innerHTML;
document.getElementById("demo2").innerHTML =
text2.toLowerCase();

}
JavaScript Search Methods
 String indexOf()
indexOf() method returns the index of (the position of)
the first occurrence of a specified text in a string.
indexOf(), and lastIndexOf() return -1 if the text is not found
 String lastIndexOf()
The lastIndexOf() methods searches backwards (from the end to
the beginning)
 String startsWith()
 String endsWith()
0
<p id="demo1"></p> 32
<p id="demo2"></p>
<p id="demo3"></p> 32
<p id="demo4"></p> 0
<p id="demo5"></p> 8
<script>
let str1 = "vellore institute of technology vellore";
document.getElementById("demo1").innerHTML = str1.indexOf("vellore");
let str2 = "vellore institute of technology vellore";
document.getElementById("demo2").innerHTML = str2.lastIndexOf("vellore");
let str3 = "vellore institute of technology vellore";
document.getElementById("demo3").innerHTML = str3.indexOf("vellore",20);
let str4 = "vellore institute of technology vellore";
document.getElementById("demo4").innerHTML = str4.lastIndexOf("vellore",
25);
let str5 = "vellore institute of technology vellore";
document.getElementById("demo5").innerHTML = str5.search("ins");
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
let text1 = "knowledge is power";
document.getElementById("demo1").innerHTML =
text1.startsWith("knowledge");
let text2 = "knowledge is power";
document.getElementById("demo2").innerHTML = text2.startsWith("vit");
let text3 = "knowledge is power";
document.getElementById("demo3").innerHTML =
text3.endsWith("power");
</script>

You might also like