SlideShare a Scribd company logo
JAVASCRIPT DOM AND REGULAR
EXPRESSIONS
By
Dr.Smitha.P.S
Associate Professor
Velammal Engineering College
• The Document Object Model (DOM) is a
programming API for HTML and XML documents.
• It defines the logical structure of documents and
the way a document is accessed and
manipulated.
• With the Document Object Model, programmers
can create and build documents, navigate their
structure, and add, modify, or delete elements
and content.
• Anything found in an HTML or XML document
can be accessed, changed, deleted, or added
using the Document Object Mode
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents:
– "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 W3C DOM standard is separated into 3 different parts:
– Core DOM - standard model for all document types
– XML DOM - standard model for XML documents
– HTML DOM - standard model for HTML documents
• 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
• In other words: The HTML DOM is a standard
for how to get, change, add, or delete HTML
elements.
• With the HTML DOM, JavaScript can access and change
all the elements of an HTML document.
• With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the
page
• JavaScript can change all the HTML attributes in the
page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and
attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the
page
• JavaScript can create new HTML events in the page
• HTML DOM Nodes
• In the HTML DOM (Document Object Model),
everything is a node:
• The document itself is a document node
• All HTML elements are element nodes
• All HTML attributes are attribute nodes
• Text inside HTML elements are text nodes
• Comments are comment nodes
• consider this table, taken from an HTML document:
• <TABLE>
• <ROWS>
• <TR>
• <TD>Shady Grove</TD>
• <TD>Aeolian</TD>
• </TR>
• <TR>
• <TD>Over the River, Charlie</TD>
• <TD>Dorian</TD>
• </TR>
• </ROWS>
• </TABLE>
• The Element Object
• In the HTML DOM, the Element object represents
an HTML element.
• Element objects can have child nodes of type
element nodes, text nodes, or comment nodes.
• A NodeList object represents a list of nodes, like
an HTML element's collection of child nodes.
• Elements can also have attributes. Attributes are
attribute nodes
• The Attr Object
• In the HTML DOM, the Attr object represents
an HTML attribute.
• An HTML attribute always belongs to an HTML
element.
• The NamedNodeMap Object
• In the HTML DOM, the NamedNodeMap
object represents an unordered collection of
an elements attribute nodes.
• Nodes in a NamedNodeMap can be accessed
by name or by index (number).
• With the HTML DOM, the document object is
your web page.
• The HTML DOM Document
• In the HTML DOM object model, the document
object represents your web page.
• The document object is the owner of all other
objects in your web page.
• If you want to access objects in an HTML page,
you always start with accessing the document
object.
• Below are some examples of how you can use
the document object to access and manipulate
HTML.
• Finding HTML Elements
• Often, with JavaScript, you want to manipulate HTML
elements.
• To do so, you have to find the elements first. There are
a couple of ways to do this:
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections
Finding HTML Element by Id
• The easiest way to find an HTML element in
the DOM, is by using the element id.
• This example finds the element with
id="intro":
• <html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
• In the example above, getElementById is a method, while innerHTML is a
property.
• The getElementById Method
– The most common way to access an HTML element is to use the id of the element.
– In the example above the getElementById method used id="demo" to find the element.
• The easiest way to get the content of an element is by using the innerHTML
property.
– The innerHTML property is useful for getting or replacing the content of HTML elements.
– The innerHTML property can be used to get or change any HTML element, including <html>
and <body>.
• <!DOCTYPE html>
• <html>
• <body>
• <p>Hello World!</p>
• <p>The DOM is very useful.</p>
• <p>This example demonstrates the <b>getElementsByTagName</b> method</p>
• <p id="demo"></p>
• <script>
• var x = document.getElementsByTagName("p");
• document.getElementById("demo").innerHTML =
• 'The first paragraph (index 0) is: ' + x[0].innerHTML;
• </script>
• </body>
• </html>
• <!DOCTYPE html>
• <html>
• <body>
• <p>Hello World!</p>
• <p class="intro">The DOM is very useful.</p>
• <p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>
• <p id="demo"></p>
• <script>
• var x = document.getElementsByClassName("intro");
• document.getElementById("demo").innerHTML =
• 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
• </script>
• </body>
• </html>
• <!DOCTYPE html>
• <html>
• <body>
• <p>Hello World!</p>
• <p class="intro">The DOM is very useful.</p>
• <p class="intro">This example demonstrates the <b>querySelectorAll</b>
method.</p>
• <p id="demo"></p>
• <script>
• var x = document.querySelectorAll("p.intro");
• document.getElementById("demo").innerHTML =
• 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
• </script>
• </body>
• </html>
• The following HTML objects (and object collections) are
also accessible:
• document. Anchors
• document. body
• document.documentElement
• document. Embeds
• document. forms
• document. Head
• document. Images
• document. Links
• document. scripts
• document. Title
JavaScript HTML DOM - Changing HTML
• In JavaScript, document.write() can be used to write
directly to the HTML output stream:
• Example
• <!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
• The easiest way to modify the content of an
HTML element is by using the innerHTML
property.
• To change the content of an HTML element,
use this syntax:
• document.getElementById(id).innerHTML =
new HTML
This example changes the content of a
<p> element:
• <html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML =
"New text!";
</script>
</body>
</html>
This example changes the content of
an <h1> element:
• <!DOCTYPE html>
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element = document.getElementById("header");
element.innerHTML = "New Header";
</script>
</body>
</html>
• Example explained:
– The HTML document above contains an <h1> element with id="header"
– We use the HTML DOM to get the element with id="header"
• A JavaScript changes the content (innerHTML) of that element
Changing the Value of an Attribute
• To change the value of an HTML attribute, use this syntax:
– document.getElementById(id).attribute=new value
• This example changes the value of the src attribute of an <img> element:
• Example
• <!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
• Example explained:
– The HTML document above contains an <img> element with id="myImage"
– We use the HTML DOM to get the element with id="myImage"
– A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"
JavaScript HTML DOM - Changing CSS
• The HTML DOM allows JavaScript to change
the style of HTML elements.
• Changing HTML Style
• To change the style of an HTML element, use
this syntax:
– document.getElementById(id).style.property=new
style
Using Events
• The HTML DOM allows you to execute code
when an event occurs.
• Events are generated by the browser when
"things happen" to HTML elements:
• An element is clicked on
• The page has loaded
• Input fields are changed
• A JavaScript can be executed when an event occurs,
like when a user clicks on an HTML element.
• To execute code when a user clicks on an element, add
JavaScript code to an HTML event attribute:
• onclick=JavaScript
• Examples of HTML events:
– When a user clicks the mouse
– When a web page has loaded
– When an image has been loaded
– When the mouse moves over an element
– When an input field is changed
– When an HTML form is submitted
– When a user strokes a key
JavaScript Output
• JavaScript can "display" data in different ways:
• Writing into an alert box, using
window.alert().
• Writing into the HTML output using
document.write().
• Writing into an HTML element, using
innerHTML.
• Writing into the browser console, using
console.log().
Using window.alert()
• You can use an alert box to display data:
• Example
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using document.write()
• For testing purposes, it is convenient to use document.write():
• Example
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using innerHTML
• To access an HTML element, JavaScript can use the document.getElementById(id)
method.
• The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
• Example
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using console.log()
• In your browser, you can use the console.log() method to display data.
• Activate the browser console with F12, and select "Console" in the menu.
• Example
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
Document tree
• The entire document is a document node
• Every HTML element is an element node
• The text inside HTML elements are text nodes
• Every HTML attribute is an attribute node
• Comments are comment nodes
Node Parents, Children, and Siblings
• The nodes in the node tree have a hierarchical relationship to each other.
• The terms parent, child, and sibling are used to describe the relationships.
Parent nodes have children. Children on the same level are called siblings
(brothers or sisters).
• In a node tree, the top node is called the root
• Every node has exactly one parent, except the root (which has no parent)
• A node can have any number of children
• Siblings are nodes with the same parent
HTML DOM Node Tree
HTML DOM Node Tree
Look at the following HTML fragment:
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
From the HTML above:
• The <html> node has no parent node; it is the root node
• The parent node of the <head> and <body> nodes is the <html> node
• The parent node of the "Hello world!" text node is the <p> node
and:
• The <html> node has two child nodes: <head> and <body>
• The <head> node has one child node: the <title> node
• The <title> node also has one child node: the text node "DOM Tutorial"
• The <h1> and <p> nodes are siblings and child nodes of <body>
and:
• The <head> element is the first child of the <html> element
• The <body> element is the last child of the <html> element
• The <h1> element is the first child of the <body> element
• The <p> element is the last child of the <body> element
Document Tree
• The HTML DOM can be accessed with JavaScript (and
other programming languages).
• All HTML elements are defined as objects, and the
programming interface is the object methods and
object properties .
• A method is an action you can do (like add or modify
an element).
• A property is a value that you can get or set (like the
name or content of a node).
The getElementById() Method
– The getElementById() method returns the element with
the specified ID:
Creating New HTML Elements (Nodes)
• To add a new element to the HTML DOM, you must create the
element (element node) first, and then append it to an existing
element.
– Example
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
• This code creates a new <p> element:
• var para = document.createElement("p");
• To add text to the <p> element, you must create a text node first. This
code creates a text node:
• var node = document.createTextNode("This is a new paragraph.");
• Then you must append the text node to the <p> element:
• para.appendChild(node);
• Finally you must append the new element to an existing element.
• This code finds an existing element:
• var element = document.getElementById("div1");
• This code appends the new element to the existing element:
• element.appendChild(para);
•
Creating new HTML Elements - insertBefore()
• The appendChild() method in the previous example, appended the new
element as the last child of the parent.
• If you don't want that you can use the insertBefore() method:
• Example
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para, child);
</script>
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
</script>
</body>
</html>
Removing Existing HTML Elements
• To remove an HTML element, you must know the
parent of the element:
• Example
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
<!DOCTYPE html>
<html>
<body>
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<button onclick="myFunction()">Remove Element</button>
<script>
function myFunction() {
var elmnt = document.getElementById("p1");
elmnt.remove();
}
</script>
</body>
</html>
Replacing HTML Elements
• To replace an element to the HTML DOM, use the replaceChild() method:
• Example
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para,child);
</script>
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
parent.replaceChild(para,child);
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<p id="intro">Hello World!</p>
<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
OutPut:
• Hello World!
• Hello World!
Document Tree: Node
Document Tree: Node
Document Tree: Node
JavaScript HTML DOM Collections
• The getElementsByTagName() method returns
an HTMLCollection object.
• An HTMLCollection object is an array-like list
(collection) of HTML elements.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
"The innerHTML of the second paragraph is: " +
myCollection[1].innerHTML;
</script>
</body>
</html>
HTML HTMLCollection Length
• The length property defines the number of elements in an HTMLCollection:
• <!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
"This document contains " + myCollection.length + " paragraphs.";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p>Click the button to change the color of all p elements.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var myCollection = document.getElementsByTagName("p");
var i;
for (i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
}
</script>
</body>
</html>
JavaScript Date Objects
• Creating Date Objects
• Date objects are created with the new Date() constructor.
• There are 4 ways to create a new date object:
• new Date()
• new Date(year, month, day, hours, minutes, seconds,
milliseconds)
• new Date(milliseconds)
• new Date(date string)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p>Using new Date(), creates a new date object with the current date
and time:</p>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
1. 7 numbers specify year, month, day, hour,
minute, second, and millisecond (in that order):
• Example
• var d = new Date(2018, 11, 24, 10, 33, 30, 0);
2. 6 numbers specify year, month, day, hour,
minute, second:
• Example
• var d = new Date(2018, 11, 24, 10, 33, 30);
3. 5 numbers specify year, month, day, hour, and
minute:
Example
var d = new Date(2018, 11, 24, 10, 33);
4. 4 numbers specify year, month, day, and hour:
Example
var d = new Date(2018, 11, 24, 10);
5. 3 numbers specify year, month, and day:
Example
var d = new Date(2018, 11, 24);
• 6. 2 numbers specify year and month:
• Example
• var d = new Date(2018, 11);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p>One parameter will be interpreted as new Date(milliseconds).</p>
<p id="demo"></p>
<script>
var d = new Date(2018);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Date Methods
• When a Date object is created, a number of methods allow you to
operate on it.
• Displaying Dates:
• JavaScript will (by default) output dates in full text string format:
• Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)
• When you display a date object in HTML, it is automatically
converted to a string, with the toString() method.
• Example
• d = new Date();
• document.getElementById("demo").innerHTML = d;
• Same as:
• d = new Date();
• document.getElementById("demo").innerHTML = d.toString();
• The toUTCString() method converts a date to a UTC string (a date
display standard).
• Example
• var d = new Date();
• document.getElementById("demo").innerHTML = d.toUTCString();
• The toDateString() method converts a date to a more readable
format:
• Example
• var d = new Date();
• document.getElementById("demo").innerHTML = d.toDateString();
JavaScript Date Formats
Type Example
ISO Date "2015-03-25" (The International Standard)
Short Date "03/25/2015"
Long Date "Mar 25 2015" or "25 Mar 2015"
JavaScript Get Date Methods
Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1,
1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Get Date Methods</h2>
<p>The internal clock in JavaScript counts from midnight January 1,
1970.</p>
<p>The getTime() function returns the number of milliseconds since
then:</p>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
document.write(d.getFullYear());
document.write("<br>");
Cont…
document.write(d.getMonth());
document.write("<br>");
var months =
["January","February","March","April","May","June","July","August","September","Oc
tober","November","December"];
document.write(months[d.getMonth()]);
document.write("<br>");
document.write(d.getDate());
document.write("<br>");
document.write(d.getHours());
</script>
</body>
</html>
JavaScript Set Date Methods
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1,
1970)
The setFullYear() method sets the year of a date object. In this example to
2020:
Example
<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>
The setMonth() method sets the month of a date object (0-11):
Example
<script>
var d = new Date();
d.setMonth(11);
document.getElementById("demo").innerHTML = d;
</script>
The setDate() Method
The setDate() method sets the day of a date object (1-31):
Example
<script>
var d = new Date();
d.setDate(15);
document.getElementById("demo").innerHTML = d;
</script>
The setDate() method can also be used to add days to a date:
Example
<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>
The setHours() Method
The setHours() method sets the hours of a date object (0-23):
Example
<script>
var d = new Date();
d.setHours(22);
document.getElementById("demo").innerHTML = d;
</script>
The setMinutes() Method
The setMinutes() method sets the minutes of a date object (0-59):
Example
<script>
var d = new Date();
d.setMinutes(30);
document.getElementById("demo").innerHTML = d;
</script>
JS OBJECTS
• Objects are variables too. But objects can contain
many values.
• This code assigns many values (Fiat, 500, white)
to a variable named car:
• var car = {type:"Fiat", model:"500",
color:"white"};
• The values are written as name:value pairs
(name and value separated by a colon).
• JavaScript objects are containers for named
values called properties or methods.
• In JavaScript, almost "everything" is an object.
• Booleans can be objects (if defined with the new keyword)
• Numbers can be objects (if defined with the new keyword)
• Strings can be objects (if defined with the new keyword)
• Dates are always objects
• Maths are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects
• All JavaScript values, except primitives, are objects.
• JavaScript Primitives
• A primitive value is a value that has no properties or methods.
• A primitive data type is data that has a primitive value.
• JavaScript defines 5 types of primitive data types:
• string
• number
• boolean
• null
• undefined
• Primitive values are immutable (they are hardcoded and therefore
cannot be changed).
Creating a JavaScript Object
• With JavaScript, you can define and create your own objects.
• There are different ways to create new objects:
• Define and create a single object, using an object literal.
• var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
• Define and create a single object, with the keyword new.
• var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
• Define an object constructor, and then create objects of the
constructed type.
• Accessing Object Properties
• You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>There are two different ways to access an object property.</p>
<p>You can use person.property or person["property"].</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>
</body>
</html>
Object Methods
• Objects can also have methods.
• Methods are actions that can be performed
on objects.
• Methods are stored in properties as function
definitions.
The this Keyword
• In a function definition, this refers to the
"owner" of the function.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
JavaScript Arrays
• JavaScript arrays are used to store multiple values in a single
variable.
• Example
• var cars = ["Saab", "Volvo", "BMW"];
• Arrays are Objects
• Arrays are a special type of objects. The typeof operator in
JavaScript returns "object" for arrays.
• Arrays use numbers to access its "elements".
• In this example, person[0] returns John:
• Array:
• var person = ["John", "Doe", 46];
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Arrays use numbers to access its elements.</p>
<p id="demo"></p>
<script>
var person = ["John", "Doe", 46];
document.getElementById("demo").innerHTML = person[0];
</script>
</body>
</html>
JavaScript Math Object
• Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of
10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Methods
Math.round(x) Returns x rounded to its nearest integer
Math.ceil(x) Returns x rounded up to its nearest integer
Math.floor(x) Returns x rounded down to its nearest integer
Math.trunc(x) Returns the integer part of x (new in ES6)
⦿ var list = [2, 4, 6, 8, 10]
⚫slice() – returns part of an array: list.slice(1,3) => array [4, 6]
⚫concat( ) – concatenates new elements to the end of the array;
returns new array: list.concat(12) => [2, 4, 6, 8, 10, 12]
⚫join( ) – creates a string from the array elements, separated by
commas (or specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10”
⚫reverse( ) – reverses order of the array elements; affects calling
array
⚫sort( ) – converts elements to strings, sorts them alphabetically
(or you can specify another order as a function); affects calling
array
⚫push( ), pop( ) – add/delete elements to the high end of array
⚫unshift( ), shift( ) – add/delete elements at the beginning of the
array
Splice() method
• Syntax
• array.splice(index, howmany, item1, ....., itemX)
• Parameter Values
• ParameterDescription
• indexRequired. An integer that specifies at what
position to add/remove items, Use negative values to
specify the position from the end of the array
• howmanyOptional. The number of items to be
removed. If set to 0, no items will be removed
• item1, ..., itemXOptional. The new item(s) to be added
to the array
Deleting Elements
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<p>Deleting elements leaves undefined holes in an array.</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML =
"The first fruit is: " + fruits[0];
delete fruits[0];
document.getElementById("demo2").innerHTML =
"The first fruit is: " + fruits[0];
</script>
</body>
</html>
Output:
JavaScript Array Methods
Deleting elements leaves undefined holes in an array.
The first fruit is: Banana
The first fruit is: undefined

More Related Content

What's hot

Bootstrap
BootstrapBootstrap
Bootstrap
Jadson Santos
 
HTML5
HTML5HTML5
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
BOSS Webtech
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
jQuery
jQueryjQuery
jQuery
Vishwa Mohan
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Json
JsonJson
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
Jalpesh Vasa
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Html, CSS & Web Designing
Html, CSS & Web DesigningHtml, CSS & Web Designing
Html, CSS & Web Designing
Leslie Steele
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
Robert MacLean
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
Vibrant Technologies & Computers
 

What's hot (20)

Bootstrap
BootstrapBootstrap
Bootstrap
 
HTML5
HTML5HTML5
HTML5
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Html presentation
Html presentationHtml presentation
Html presentation
 
Js ppt
Js pptJs ppt
Js ppt
 
jQuery
jQueryjQuery
jQuery
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Json
JsonJson
Json
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Html, CSS & Web Designing
Html, CSS & Web DesigningHtml, CSS & Web Designing
Html, CSS & Web Designing
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 

Similar to Dom date and objects and event handling

Web technologies-course 09.pptx
Web technologies-course 09.pptxWeb technologies-course 09.pptx
Web technologies-course 09.pptx
Stefan Oprea
 
WEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxWEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptx
karthiksmart21
 
Javascript part 2 DOM.pptx
Javascript part 2 DOM.pptxJavascript part 2 DOM.pptx
Javascript part 2 DOM.pptx
deepa339830
 
DOM(Document Object Model) in javascript
DOM(Document Object Model) in javascriptDOM(Document Object Model) in javascript
DOM(Document Object Model) in javascript
Rashmi Mishra
 
Web Technology Part 3
Web Technology Part 3Web Technology Part 3
Web Technology Part 3
Thapar Institute
 
Build Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponentsBuild Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponents
Gil Fink
 
WEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSISWEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSIS
sweetysweety8
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
Lilia Sfaxi
 
Part 7
Part 7Part 7
Part 7
NOHA AW
 
The Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedThe Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has Arrived
Gil Fink
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
GOPAL BASAK
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document Object
Arti Parab Academics
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
Partnered Health
 
Web components
Web componentsWeb components
Web components
Gil Fink
 
Lab1_HTML.pptx
Lab1_HTML.pptxLab1_HTML.pptx
Lab1_HTML.pptx
IslamGhonimi1
 
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptxDESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
bmit1
 
Lab_Ex1.pptx
Lab_Ex1.pptxLab_Ex1.pptx
Lab_Ex1.pptx
sherrilsiddhardh
 
Code & Design your first website 4/18
Code & Design your first website 4/18Code & Design your first website 4/18
Code & Design your first website 4/18
TJ Stalcup
 
Web component driven development
Web component driven developmentWeb component driven development
Web component driven development
Gil Fink
 

Similar to Dom date and objects and event handling (20)

Web technologies-course 09.pptx
Web technologies-course 09.pptxWeb technologies-course 09.pptx
Web technologies-course 09.pptx
 
WEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxWEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptx
 
Javascript part 2 DOM.pptx
Javascript part 2 DOM.pptxJavascript part 2 DOM.pptx
Javascript part 2 DOM.pptx
 
DOM(Document Object Model) in javascript
DOM(Document Object Model) in javascriptDOM(Document Object Model) in javascript
DOM(Document Object Model) in javascript
 
Web Technology Part 3
Web Technology Part 3Web Technology Part 3
Web Technology Part 3
 
Build Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponentsBuild Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponents
 
WEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSISWEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSIS
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Part 7
Part 7Part 7
Part 7
 
The Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedThe Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has Arrived
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document Object
 
Dom
DomDom
Dom
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
Web components
Web componentsWeb components
Web components
 
Lab1_HTML.pptx
Lab1_HTML.pptxLab1_HTML.pptx
Lab1_HTML.pptx
 
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptxDESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
DESIGN THINKING SYLLABUS MATERIAL NOTES UNIT 1 .pptx
 
Lab_Ex1.pptx
Lab_Ex1.pptxLab_Ex1.pptx
Lab_Ex1.pptx
 
Code & Design your first website 4/18
Code & Design your first website 4/18Code & Design your first website 4/18
Code & Design your first website 4/18
 
Web component driven development
Web component driven developmentWeb component driven development
Web component driven development
 

More from smitha273566

Web services
Web servicesWeb services
Web services
smitha273566
 
Web essentials clients, servers and communication – the internet – basic inte...
Web essentials clients, servers and communication – the internet – basic inte...Web essentials clients, servers and communication – the internet – basic inte...
Web essentials clients, servers and communication – the internet – basic inte...
smitha273566
 
Unit iv xml
Unit iv xmlUnit iv xml
Unit iv xml
smitha273566
 
Unit iv xml dom
Unit iv xml domUnit iv xml dom
Unit iv xml dom
smitha273566
 
Regular expression unit2
Regular expression unit2Regular expression unit2
Regular expression unit2
smitha273566
 
Html (1)
Html (1)Html (1)
Html (1)
smitha273566
 
Cascading style sheets
Cascading style sheetsCascading style sheets
Cascading style sheets
smitha273566
 
Soa unit iv
Soa unit ivSoa unit iv
Soa unit iv
smitha273566
 
Unit iii soa
Unit iii soaUnit iii soa
Unit iii soa
smitha273566
 
It8074 soa-unit i
It8074 soa-unit iIt8074 soa-unit i
It8074 soa-unit i
smitha273566
 

More from smitha273566 (10)

Web services
Web servicesWeb services
Web services
 
Web essentials clients, servers and communication – the internet – basic inte...
Web essentials clients, servers and communication – the internet – basic inte...Web essentials clients, servers and communication – the internet – basic inte...
Web essentials clients, servers and communication – the internet – basic inte...
 
Unit iv xml
Unit iv xmlUnit iv xml
Unit iv xml
 
Unit iv xml dom
Unit iv xml domUnit iv xml dom
Unit iv xml dom
 
Regular expression unit2
Regular expression unit2Regular expression unit2
Regular expression unit2
 
Html (1)
Html (1)Html (1)
Html (1)
 
Cascading style sheets
Cascading style sheetsCascading style sheets
Cascading style sheets
 
Soa unit iv
Soa unit ivSoa unit iv
Soa unit iv
 
Unit iii soa
Unit iii soaUnit iii soa
Unit iii soa
 
It8074 soa-unit i
It8074 soa-unit iIt8074 soa-unit i
It8074 soa-unit i
 

Recently uploaded

power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 

Recently uploaded (20)

power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 

Dom date and objects and event handling

  • 1. JAVASCRIPT DOM AND REGULAR EXPRESSIONS By Dr.Smitha.P.S Associate Professor Velammal Engineering College
  • 2. • The Document Object Model (DOM) is a programming API for HTML and XML documents. • It defines the logical structure of documents and the way a document is accessed and manipulated. • With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. • Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Mode
  • 3. • The DOM is a W3C (World Wide Web Consortium) standard. • The DOM defines a standard for accessing documents: – "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 W3C DOM standard is separated into 3 different parts: – Core DOM - standard model for all document types – XML DOM - standard model for XML documents – HTML DOM - standard model for HTML documents
  • 4. • 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 • In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
  • 5. • With the HTML DOM, JavaScript can access and change all the elements of an HTML document. • With the object model, JavaScript gets all the power it needs to create dynamic HTML: • JavaScript can change all the HTML elements in the page • JavaScript can change all the HTML attributes in the page • JavaScript can change all the CSS styles in the page • JavaScript can remove existing HTML elements and attributes • JavaScript can add new HTML elements and attributes • JavaScript can react to all existing HTML events in the page • JavaScript can create new HTML events in the page
  • 6. • HTML DOM Nodes • In the HTML DOM (Document Object Model), everything is a node: • The document itself is a document node • All HTML elements are element nodes • All HTML attributes are attribute nodes • Text inside HTML elements are text nodes • Comments are comment nodes
  • 7.
  • 8. • consider this table, taken from an HTML document: • <TABLE> • <ROWS> • <TR> • <TD>Shady Grove</TD> • <TD>Aeolian</TD> • </TR> • <TR> • <TD>Over the River, Charlie</TD> • <TD>Dorian</TD> • </TR> • </ROWS> • </TABLE>
  • 9.
  • 10. • The Element Object • In the HTML DOM, the Element object represents an HTML element. • Element objects can have child nodes of type element nodes, text nodes, or comment nodes. • A NodeList object represents a list of nodes, like an HTML element's collection of child nodes. • Elements can also have attributes. Attributes are attribute nodes
  • 11. • The Attr Object • In the HTML DOM, the Attr object represents an HTML attribute. • An HTML attribute always belongs to an HTML element. • The NamedNodeMap Object • In the HTML DOM, the NamedNodeMap object represents an unordered collection of an elements attribute nodes. • Nodes in a NamedNodeMap can be accessed by name or by index (number).
  • 12. • With the HTML DOM, the document object is your web page. • The HTML DOM Document • In the HTML DOM object model, the document object represents your web page. • The document object is the owner of all other objects in your web page. • If you want to access objects in an HTML page, you always start with accessing the document object. • Below are some examples of how you can use the document object to access and manipulate HTML.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17. • Finding HTML Elements • Often, with JavaScript, you want to manipulate HTML elements. • To do so, you have to find the elements first. There are a couple of ways to do this: • Finding HTML elements by id • Finding HTML elements by tag name • Finding HTML elements by class name • Finding HTML elements by CSS selectors • Finding HTML elements by HTML object collections
  • 18. Finding HTML Element by Id • The easiest way to find an HTML element in the DOM, is by using the element id. • This example finds the element with id="intro":
  • 19. • <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> • In the example above, getElementById is a method, while innerHTML is a property. • The getElementById Method – The most common way to access an HTML element is to use the id of the element. – In the example above the getElementById method used id="demo" to find the element. • The easiest way to get the content of an element is by using the innerHTML property. – The innerHTML property is useful for getting or replacing the content of HTML elements. – The innerHTML property can be used to get or change any HTML element, including <html> and <body>.
  • 20. • <!DOCTYPE html> • <html> • <body> • <p>Hello World!</p> • <p>The DOM is very useful.</p> • <p>This example demonstrates the <b>getElementsByTagName</b> method</p> • <p id="demo"></p> • <script> • var x = document.getElementsByTagName("p"); • document.getElementById("demo").innerHTML = • 'The first paragraph (index 0) is: ' + x[0].innerHTML; • </script> • </body> • </html>
  • 21. • <!DOCTYPE html> • <html> • <body> • <p>Hello World!</p> • <p class="intro">The DOM is very useful.</p> • <p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p> • <p id="demo"></p> • <script> • var x = document.getElementsByClassName("intro"); • document.getElementById("demo").innerHTML = • 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; • </script> • </body> • </html>
  • 22. • <!DOCTYPE html> • <html> • <body> • <p>Hello World!</p> • <p class="intro">The DOM is very useful.</p> • <p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p> • <p id="demo"></p> • <script> • var x = document.querySelectorAll("p.intro"); • document.getElementById("demo").innerHTML = • 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; • </script> • </body> • </html>
  • 23. • The following HTML objects (and object collections) are also accessible: • document. Anchors • document. body • document.documentElement • document. Embeds • document. forms • document. Head • document. Images • document. Links • document. scripts • document. Title
  • 24. JavaScript HTML DOM - Changing HTML • In JavaScript, document.write() can be used to write directly to the HTML output stream: • Example • <!DOCTYPE html> <html> <body> <script> document.write(Date()); </script> </body> </html>
  • 25. • The easiest way to modify the content of an HTML element is by using the innerHTML property. • To change the content of an HTML element, use this syntax: • document.getElementById(id).innerHTML = new HTML
  • 26. This example changes the content of a <p> element: • <html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> </body> </html>
  • 27. This example changes the content of an <h1> element: • <!DOCTYPE html> <html> <body> <h1 id="header">Old Header</h1> <script> var element = document.getElementById("header"); element.innerHTML = "New Header"; </script> </body> </html> • Example explained: – The HTML document above contains an <h1> element with id="header" – We use the HTML DOM to get the element with id="header" • A JavaScript changes the content (innerHTML) of that element
  • 28. Changing the Value of an Attribute • To change the value of an HTML attribute, use this syntax: – document.getElementById(id).attribute=new value • This example changes the value of the src attribute of an <img> element: • Example • <!DOCTYPE html> <html> <body> <img id="myImage" src="smiley.gif"> <script> document.getElementById("myImage").src = "landscape.jpg"; </script> </body> </html> • Example explained: – The HTML document above contains an <img> element with id="myImage" – We use the HTML DOM to get the element with id="myImage" – A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"
  • 29. JavaScript HTML DOM - Changing CSS • The HTML DOM allows JavaScript to change the style of HTML elements. • Changing HTML Style • To change the style of an HTML element, use this syntax: – document.getElementById(id).style.property=new style
  • 30. Using Events • The HTML DOM allows you to execute code when an event occurs. • Events are generated by the browser when "things happen" to HTML elements: • An element is clicked on • The page has loaded • Input fields are changed
  • 31. • A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. • To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: • onclick=JavaScript • Examples of HTML events: – When a user clicks the mouse – When a web page has loaded – When an image has been loaded – When the mouse moves over an element – When an input field is changed – When an HTML form is submitted – When a user strokes a key
  • 32. JavaScript Output • JavaScript can "display" data in different ways: • Writing into an alert box, using window.alert(). • Writing into the HTML output using document.write(). • Writing into an HTML element, using innerHTML. • Writing into the browser console, using console.log().
  • 33. Using window.alert() • You can use an alert box to display data: • Example • <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> </html>
  • 34. Using document.write() • For testing purposes, it is convenient to use document.write(): • Example • <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body> </html>
  • 35. Using innerHTML • To access an HTML element, JavaScript can use the document.getElementById(id) method. • The id attribute defines the HTML element. The innerHTML property defines the HTML content: • Example • <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> </body> </html>
  • 36. Using console.log() • In your browser, you can use the console.log() method to display data. • Activate the browser console with F12, and select "Console" in the menu. • Example • <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> console.log(5 + 6); </script> </body> </html>
  • 37. Document tree • The entire document is a document node • Every HTML element is an element node • The text inside HTML elements are text nodes • Every HTML attribute is an attribute node • Comments are comment nodes Node Parents, Children, and Siblings • The nodes in the node tree have a hierarchical relationship to each other. • The terms parent, child, and sibling are used to describe the relationships. Parent nodes have children. Children on the same level are called siblings (brothers or sisters). • In a node tree, the top node is called the root • Every node has exactly one parent, except the root (which has no parent) • A node can have any number of children • Siblings are nodes with the same parent
  • 39. HTML DOM Node Tree Look at the following HTML fragment: <html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body> </html> From the HTML above: • The <html> node has no parent node; it is the root node • The parent node of the <head> and <body> nodes is the <html> node • The parent node of the "Hello world!" text node is the <p> node and: • The <html> node has two child nodes: <head> and <body> • The <head> node has one child node: the <title> node • The <title> node also has one child node: the text node "DOM Tutorial" • The <h1> and <p> nodes are siblings and child nodes of <body> and: • The <head> element is the first child of the <html> element • The <body> element is the last child of the <html> element • The <h1> element is the first child of the <body> element • The <p> element is the last child of the <body> element
  • 40. Document Tree • The HTML DOM can be accessed with JavaScript (and other programming languages). • All HTML elements are defined as objects, and the programming interface is the object methods and object properties . • A method is an action you can do (like add or modify an element). • A property is a value that you can get or set (like the name or content of a node). The getElementById() Method – The getElementById() method returns the element with the specified ID:
  • 41.
  • 42. Creating New HTML Elements (Nodes) • To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element. – Example • <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); </script>
  • 43. <!DOCTYPE html> <html> <body> <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); </script> </body> </html>
  • 44. • This code creates a new <p> element: • var para = document.createElement("p"); • To add text to the <p> element, you must create a text node first. This code creates a text node: • var node = document.createTextNode("This is a new paragraph."); • Then you must append the text node to the <p> element: • para.appendChild(node); • Finally you must append the new element to an existing element. • This code finds an existing element: • var element = document.getElementById("div1"); • This code appends the new element to the existing element: • element.appendChild(para); •
  • 45. Creating new HTML Elements - insertBefore() • The appendChild() method in the previous example, appended the new element as the last child of the parent. • If you don't want that you can use the insertBefore() method: • Example • <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); var child = document.getElementById("p1"); element.insertBefore(para, child); </script>
  • 46. <!DOCTYPE html> <html> <body> <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); var child = document.getElementById("p1"); element.insertBefore(para,child); </script> </body> </html>
  • 47. Removing Existing HTML Elements • To remove an HTML element, you must know the parent of the element: • Example • <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.removeChild(child); </script>
  • 48. <!DOCTYPE html> <html> <body> <div> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <button onclick="myFunction()">Remove Element</button> <script> function myFunction() { var elmnt = document.getElementById("p1"); elmnt.remove(); } </script> </body> </html>
  • 49. Replacing HTML Elements • To replace an element to the HTML DOM, use the replaceChild() method: • Example • <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.replaceChild(para,child); </script>
  • 50. <!DOCTYPE html> <html> <body> <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var parent = document.getElementById("div1"); var child = document.getElementById("p1"); var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); parent.replaceChild(para,child); </script> </body> </html>
  • 51. Example <!DOCTYPE html> <html> <body> <p id="intro">Hello World!</p> <script> x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); </script> </body> </html> OutPut: • Hello World! • Hello World!
  • 55. JavaScript HTML DOM Collections • The getElementsByTagName() method returns an HTMLCollection object. • An HTMLCollection object is an array-like list (collection) of HTML elements.
  • 56. <!DOCTYPE html> <html> <body> <h2>JavaScript HTML DOM</h2> <p>Hello World!</p> <p>Hello Norway!</p> <p id="demo"></p> <script> var myCollection = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = "The innerHTML of the second paragraph is: " + myCollection[1].innerHTML; </script> </body> </html>
  • 57. HTML HTMLCollection Length • The length property defines the number of elements in an HTMLCollection: • <!DOCTYPE html> <html> <body> <h2>JavaScript HTML DOM</h2> <p>Hello World!</p> <p>Hello Norway!</p> <p id="demo"></p> <script> var myCollection = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = "This document contains " + myCollection.length + " paragraphs."; </script> </body> </html>
  • 58. <!DOCTYPE html> <html> <body> <h2>JavaScript HTML DOM</h2> <p>Hello World!</p> <p>Hello Norway!</p> <p>Click the button to change the color of all p elements.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var myCollection = document.getElementsByTagName("p"); var i; for (i = 0; i < myCollection.length; i++) { myCollection[i].style.color = "red"; } } </script> </body> </html>
  • 59. JavaScript Date Objects • Creating Date Objects • Date objects are created with the new Date() constructor. • There are 4 ways to create a new date object: • new Date() • new Date(year, month, day, hours, minutes, seconds, milliseconds) • new Date(milliseconds) • new Date(date string)
  • 60. <!DOCTYPE html> <html> <body> <h2>JavaScript new Date()</h2> <p>Using new Date(), creates a new date object with the current date and time:</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d; </script> </body> </html>
  • 61. 1. 7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order): • Example • var d = new Date(2018, 11, 24, 10, 33, 30, 0); 2. 6 numbers specify year, month, day, hour, minute, second: • Example • var d = new Date(2018, 11, 24, 10, 33, 30);
  • 62. 3. 5 numbers specify year, month, day, hour, and minute: Example var d = new Date(2018, 11, 24, 10, 33); 4. 4 numbers specify year, month, day, and hour: Example var d = new Date(2018, 11, 24, 10); 5. 3 numbers specify year, month, and day: Example var d = new Date(2018, 11, 24);
  • 63. • 6. 2 numbers specify year and month: • Example • var d = new Date(2018, 11);
  • 64. <!DOCTYPE html> <html> <body> <h2>JavaScript new Date()</h2> <p>One parameter will be interpreted as new Date(milliseconds).</p> <p id="demo"></p> <script> var d = new Date(2018); document.getElementById("demo").innerHTML = d; </script> </body> </html>
  • 65. Date Methods • When a Date object is created, a number of methods allow you to operate on it. • Displaying Dates: • JavaScript will (by default) output dates in full text string format: • Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time) • When you display a date object in HTML, it is automatically converted to a string, with the toString() method. • Example • d = new Date(); • document.getElementById("demo").innerHTML = d; • Same as: • d = new Date(); • document.getElementById("demo").innerHTML = d.toString();
  • 66. • The toUTCString() method converts a date to a UTC string (a date display standard). • Example • var d = new Date(); • document.getElementById("demo").innerHTML = d.toUTCString(); • The toDateString() method converts a date to a more readable format: • Example • var d = new Date(); • document.getElementById("demo").innerHTML = d.toDateString();
  • 67. JavaScript Date Formats Type Example ISO Date "2015-03-25" (The International Standard) Short Date "03/25/2015" Long Date "Mar 25 2015" or "25 Mar 2015"
  • 68. JavaScript Get Date Methods Method Description getFullYear() Get the year as a four digit number (yyyy) getMonth() Get the month as a number (0-11) getDate() Get the day as a number (1-31) getHours() Get the hour (0-23) getMinutes() Get the minute (0-59) getSeconds() Get the second (0-59) getMilliseconds() Get the millisecond (0-999) getTime() Get the time (milliseconds since January 1, 1970) getDay() Get the weekday as a number (0-6) Date.now() Get the time. ECMAScript 5.
  • 69. <!DOCTYPE html> <html> <body> <h2>JavaScript Get Date Methods</h2> <p>The internal clock in JavaScript counts from midnight January 1, 1970.</p> <p>The getTime() function returns the number of milliseconds since then:</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getTime(); document.write(d.getFullYear()); document.write("<br>");
  • 71. JavaScript Set Date Methods Method Description setDate() Set the day as a number (1-31) setFullYear() Set the year (optionally month and day) setHours() Set the hour (0-23) setMilliseconds() Set the milliseconds (0-999) setMinutes() Set the minutes (0-59) setMonth() Set the month (0-11) setSeconds() Set the seconds (0-59) setTime() Set the time (milliseconds since January 1, 1970)
  • 72. The setFullYear() method sets the year of a date object. In this example to 2020: Example <script> var d = new Date(); d.setFullYear(2020); document.getElementById("demo").innerHTML = d; </script> The setMonth() method sets the month of a date object (0-11): Example <script> var d = new Date(); d.setMonth(11); document.getElementById("demo").innerHTML = d; </script>
  • 73. The setDate() Method The setDate() method sets the day of a date object (1-31): Example <script> var d = new Date(); d.setDate(15); document.getElementById("demo").innerHTML = d; </script> The setDate() method can also be used to add days to a date: Example <script> var d = new Date(); d.setDate(d.getDate() + 50); document.getElementById("demo").innerHTML = d; </script>
  • 74. The setHours() Method The setHours() method sets the hours of a date object (0-23): Example <script> var d = new Date(); d.setHours(22); document.getElementById("demo").innerHTML = d; </script> The setMinutes() Method The setMinutes() method sets the minutes of a date object (0-59): Example <script> var d = new Date(); d.setMinutes(30); document.getElementById("demo").innerHTML = d; </script>
  • 75. JS OBJECTS • Objects are variables too. But objects can contain many values. • This code assigns many values (Fiat, 500, white) to a variable named car: • var car = {type:"Fiat", model:"500", color:"white"}; • The values are written as name:value pairs (name and value separated by a colon). • JavaScript objects are containers for named values called properties or methods.
  • 76. • In JavaScript, almost "everything" is an object. • Booleans can be objects (if defined with the new keyword) • Numbers can be objects (if defined with the new keyword) • Strings can be objects (if defined with the new keyword) • Dates are always objects • Maths are always objects • Regular expressions are always objects • Arrays are always objects • Functions are always objects • Objects are always objects • All JavaScript values, except primitives, are objects.
  • 77. • JavaScript Primitives • A primitive value is a value that has no properties or methods. • A primitive data type is data that has a primitive value. • JavaScript defines 5 types of primitive data types: • string • number • boolean • null • undefined • Primitive values are immutable (they are hardcoded and therefore cannot be changed).
  • 78. Creating a JavaScript Object • With JavaScript, you can define and create your own objects. • There are different ways to create new objects: • Define and create a single object, using an object literal. • var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; • Define and create a single object, with the keyword new. • var person = new Object(); person.firstName = "John"; person.lastName = "Doe"; person.age = 50; person.eyeColor = "blue"; • Define an object constructor, and then create objects of the constructed type.
  • 79. • Accessing Object Properties • You can access object properties in two ways: objectName.propertyName or objectName["propertyName"]
  • 80. <!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>There are two different ways to access an object property.</p> <p>You can use person.property or person["property"].</p> <p id="demo"></p> <script> // Create an object: var person = { firstName: "John", lastName : "Doe", id : 5566 }; // Display some data from the object: document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName; </script> </body> </html>
  • 81. Object Methods • Objects can also have methods. • Methods are actions that can be performed on objects. • Methods are stored in properties as function definitions. The this Keyword • In a function definition, this refers to the "owner" of the function.
  • 82. <!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>An object method is a function definition, stored as a property value.</p> <p id="demo"></p> <script> // Create an object: var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; // Display data from the object: document.getElementById("demo").innerHTML = person.fullName(); </script> </body> </html>
  • 83. JavaScript Arrays • JavaScript arrays are used to store multiple values in a single variable. • Example • var cars = ["Saab", "Volvo", "BMW"]; • Arrays are Objects • Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. • Arrays use numbers to access its "elements". • In this example, person[0] returns John: • Array: • var person = ["John", "Doe", 46];
  • 84. <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>Arrays use numbers to access its elements.</p> <p id="demo"></p> <script> var person = ["John", "Doe", 46]; document.getElementById("demo").innerHTML = person[0]; </script> </body> </html>
  • 85. JavaScript Math Object • Math.E // returns Euler's number Math.PI // returns PI Math.SQRT2 // returns the square root of 2 Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 // returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of E
  • 86. Math Methods Math.round(x) Returns x rounded to its nearest integer Math.ceil(x) Returns x rounded up to its nearest integer Math.floor(x) Returns x rounded down to its nearest integer Math.trunc(x) Returns the integer part of x (new in ES6)
  • 87. ⦿ var list = [2, 4, 6, 8, 10] ⚫slice() – returns part of an array: list.slice(1,3) => array [4, 6] ⚫concat( ) – concatenates new elements to the end of the array; returns new array: list.concat(12) => [2, 4, 6, 8, 10, 12] ⚫join( ) – creates a string from the array elements, separated by commas (or specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10” ⚫reverse( ) – reverses order of the array elements; affects calling array ⚫sort( ) – converts elements to strings, sorts them alphabetically (or you can specify another order as a function); affects calling array ⚫push( ), pop( ) – add/delete elements to the high end of array ⚫unshift( ), shift( ) – add/delete elements at the beginning of the array
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93. Splice() method • Syntax • array.splice(index, howmany, item1, ....., itemX) • Parameter Values • ParameterDescription • indexRequired. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array • howmanyOptional. The number of items to be removed. If set to 0, no items will be removed • item1, ..., itemXOptional. The new item(s) to be added to the array
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100. Deleting Elements <!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <p>Deleting elements leaves undefined holes in an array.</p> <p id="demo1"></p> <p id="demo2"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = "The first fruit is: " + fruits[0]; delete fruits[0]; document.getElementById("demo2").innerHTML = "The first fruit is: " + fruits[0]; </script> </body> </html> Output: JavaScript Array Methods Deleting elements leaves undefined holes in an array. The first fruit is: Banana The first fruit is: undefined