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

Dom date and objects and event handling

  • 1.
    JAVASCRIPT DOM ANDREGULAR EXPRESSIONS By Dr.Smitha.P.S Associate Professor Velammal Engineering College
  • 2.
    • The DocumentObject 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 DOMis 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 HTMLDOM 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 theHTML 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 DOMNodes • 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
  • 8.
    • consider thistable, 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>
  • 10.
    • The ElementObject • 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 AttrObject • 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 theHTML 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.
  • 17.
    • Finding HTMLElements • 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 Elementby 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 followingHTML 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 easiestway 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 changesthe 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 changesthe 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 Valueof 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 • TheHTML 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 JavaScriptcan 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 • JavaScriptcan "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() • Youcan 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() • Fortesting 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 • Toaccess 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() • Inyour 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 • Theentire 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
  • 38.
  • 39.
    HTML DOM NodeTree 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 • TheHTML 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:
  • 42.
    Creating New HTMLElements (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"> <pid="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 codecreates 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 HTMLElements - 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"> <pid="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 HTMLElements • 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">Thisis 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"> <pid="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">HelloWorld!</p> <script> x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); </script> </body> </html> OutPut: • Hello World! • Hello World!
  • 52.
  • 53.
  • 54.
  • 55.
    JavaScript HTML DOMCollections • 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 HTMLDOM</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 HTMLDOM</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 newDate()</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 numbersspecify 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 numbersspecify 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. 2numbers specify year and month: • Example • var d = new Date(2018, 11);
  • 64.
    <!DOCTYPE html> <html> <body> <h2>JavaScript newDate()</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 • Whena 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 TypeExample 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 DateMethods 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 GetDate 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>");
  • 70.
  • 71.
    JavaScript Set DateMethods 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() methodsets 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 ThesetDate() 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 ThesetHours() 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 • Objectsare 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 JavaScriptObject • 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 ObjectProperties • You can access object properties in two ways: objectName.propertyName or objectName["propertyName"]
  • 80.
    <!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>Thereare 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 • Objectscan 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>Anobject 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 • JavaScriptarrays 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>Arraysuse 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) Returnsx 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
  • 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
  • 100.
    Deleting Elements <!DOCTYPE html> <html> <body> <h2>JavaScriptArray 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