SlideShare a Scribd company logo
Team Emertxe
www.webstackacademy.com
Document Object Model
JavaScript
www.webstackacademy.com ‹#›www.webstackacademy.com
Introduction
(DOM)
What is DOM?
 The Document Object Model (DOM) is a cross-platform and language-independent
application programming interface.
 The DOM, is the API through which JavaScript interacts with content within a
website.
 The DOM API is used to access, traverse and manipulate HTML and XML
documents.
 The DOM is a W3C (World Wide Web Consortium) standard.
What is DOM Tree?
• The DOM treats an HTML, XHTML, or XML document as a tree
• structure
• Each node is an object representing a part of the document
• User case of HTML, XML and XHTML are different but DOM acts as a
common standard
HTML DOM Tree Objects
Types of DOM nodes
 Element nodes (HTML tag): Can have children / attributes.
 Text nodes: Text nodes are contained within element nodes and
cannot have child elements. Text nodes means all the text within
nodes.
 Attribute nodes (Attribute / Value pairs): Text / Attributes are
children of element node, they cannot further have children or
attributes
DOM standards
DOM level 0:
• Earliest implementation of DOM
• There existed no standard when its was implemented in some of the major browsers before 1998
DOM level 1
• It was recommended by W3C in 1998
• It will provide complete model for an entire HTML or XML document, to change any portion of the
document
DOM level 2
• It was published in 2000 by introducing additional features – getElementById, Event model,
XML namespace (Avoiding name conflicts), Stylesheet
DOM standards
DOM level 0:
• Earliest implementation of DOM
• There existed no standard when its was implemented in some of the major browsers before 1998
DOM level 1
• It was recommended by W3C in 1998
• It will provide complete model for an entire HTML or XML document, to change any portion of the
document
DOM level 2
• It was published in 2000 by introducing additional features – getElementById, Event model,
• XML namespace (Avoiding name conflicts), Stylesheet
DOM standards
DOM level 3
• It was published in 2004
• Added support for Xpath (Navigating between multiple nodes in XML)
• Keyboard event handling
DOM level 4
• It was published in 2015
• Latest version of DOM
www.webstackacademy.com ‹#›www.webstackacademy.com
Methods
(APIs in DOM)
DOM methods
• HTML DOM Methods are actions we can perform on HTML elements
• HTML DOM Properties are values that we can set or change
<script>
document.getElementById("ex").innerHTML = "Hello World!";
</script>
• getElementById -> Method
• innerHTML -> Property
DOM Methods
getElementById()
• Accesses any element on the page via its ID attribute
• A fundamental method within the DOM for accessing elements on the page
• This method will returns single element
innerHTML
• The innerHTML is used to get and replace the content of HTML elements.
DOM Element
getElementsByName(name)
Returns an list with the given name attribute
getElementsByTagName(name)
Returns a list of elements with the given tag name.
var allParagraphs = document.getElementsByTagName(“p”);
var allParagraphs = document.getElementsByName(“number”);
Element by class name
getElementsByClassName()
Returns a list of all elements with given class name
var elements = document.getElementsByClassName(“example”);
DOM Example
<script>
function GetById(){
document.getElementById("div1").innerHTML=document.getElementById("num").value;
}
function GetByName()
{
var nums= document.getElementsByName("number");
var res='';
for(var i=0; i<nums.length; i++)
{
res+=nums[i].value +"<br/>";
document.getElementById("div1").innerHTML= res;
}
}
</script>
DOM Example
<body>
<form id="form1">
<div>
<input type="text" id="num" value="12345" />
<input type="text" name="number" value="num1" />
<input type="text" name="number" value="num2" />
<input type="text" name="number" value="num3" />
</div>
<br />
<div id="div1" style="border-style: solid; border-width: thick; border-color: blue;
width: 515px; height: 100px;">
Div Section
</div>
<br />
<input type="button" onclick="GetById();" value="Get Element By Id" />
<input type="button" onclick="GetByName();" value="Get Element By Name" />
</form>
</body>
Elements by CSS Selectors
querySelector()
Returns the first match of the passed selector string
firstMatchElement = document.querySelector(“.example”);
querySelectorAll()
Returns a NodeList of DOM elements that match the query
allMatchElements = document.querySelectorAll(“.example");
Exercise
• Write a JavaScript program to modify the text-align, font-size, font-family of
heading1 using getElementById
• Write a JavaScript program to change the background color of all the <div>
tag
• Write a JavaScript to add the text shadow in all paragraphs in the given
essay
Some useful tips:
• <element-name>.style.textShadow = “Apx Bpx” will set you the shadow
www.webstackacademy.com ‹#›www.webstackacademy.com
Documents
(Manipulating documents using DOM APIs)
Documents
• Web browser window is represented by window object
• Every window has a document property that refers to document
objects
• The document objects represents the web page
• We can access and manipulate HTML using document objects
Changing HTML elements
Methods Description
EvalError Change the inner HTML of an HTML element
RangeError Change the attribute value of an HTML element
ReferenceError Changes the attribute value of an HTML element
SyntaxError
TypeError
Adding and Deleting Element
Methods Description
document.createElement() Create an HTML Element
document.removeChild() Remove an HTML Element
document.appendChild() Add an HTML Element
document.replaceChild() Replace an HTML Element
document.write() Write into the HTML output stream
document.insertBefore() Insert before an HTML element
Adding Event Handlers
Methods Description
Document.getElementById(id).onclick =
function()
{
// Code here…
}
Adding an event hander on mouse clicking
HTML DOM – Handling images
<html>
<script>
function imgFunc()
{
document.getElementById(“myimage").src = “jobsold.jpg";
}
</script>
<body>
<img id=“myimage" src=“jobsyoung.jpg" width=500 height=200>
<button onclick="imgFunc()">Click Here to change image</button>
</body>
</html>
HTML DOM – Table manipulation
• The Table object of the DOM supports dynamically generate a table or certain rows/columns
• We can access a <table> element by using getElementbyId()
Method Description
createCaption() Creates an empty <caption> elements and adds it to the table
deleteCaption() Removes the first caption element from the table
insertRow() Inserts new row in the specific index
deleteRow() Removes a row from the table
insertCell() Inserts new column in the specific row
createTHead() Creates an empty <thead> elements and adds it to the table
deleteTHead() Removes the <thead> element from the table
createTFoot() Creates an empty <tfoot> elements and adds it to the table
deleteTFoot() Removes the <tfoot> element from the table
www.webstackacademy.com
HTML DOM – Table - Relationship view
Exercise
• Modify IPL table manipulation program with following options:
 Taking user input for new row addition (instead of hard-coded value)
 Adding new column in all rows called “City” and populate the city name the team belongs to
 Add option to delete the column by taking the column index from the user
 Insert table head as “IPL Team details” with appropriate column names (Name, Team, Captain etc..)
Some useful tips:
• <table-name>.rows.length will give you number of rows
• <table-name>.rows[0].cells.length will give you number of columns
www.webstackacademy.com ‹#›www.webstackacademy.com
JavaScript Animation
(DOM – Animation APIs)
JavaScript Animation
• The JavaScript animation is implemented as gradual changing of DOM element
styles or canvas objects
• The whole process is split into pieces, and each piece is called by timer
• An animation is created by replacing one Image frame with another at speed such
that it appears to be a moving Image
• Animations can be created using JavaScript by using a timer which replaces one
image frame with another
• The two timer function setTimeout() and setInterval() to execute JavaScript codes
at set intervals
DOM Animation
Method Description
setTimeout(function,duration) This function calls function after duration milliseconds from
now
setInterval(function,duration) This function calls function after every duration milliseconds
clearTimeout(timeout) This function calls clears any timer set by the setTimeout()
functions
Some useful tips:
• <element-name>.style.left = A px sets the left position of the element
• <element-name>.style.right = A px sets the right position of the element
• <element-name>.style.top = A px sets the top position of the element
• <element-name>.style.bottom = A px sets the top position of the element
Exercise
• Write a JavaScript program to move two small squares inside one big square
in a random manner. User should be able to start and stop this animation
using button based events
Some useful tips:
Math.floor(Math.random() * Math.floor(max)) will give you a
random number that is less than max value
www.webstackacademy.com ‹#›www.webstackacademy.com
Node & NodeList Handling
DOM – Node Handling APIs
DOM Nodes
• In the context of DOM, every entity in an HTML or XML document, is referred as a
Node
• In JavaScript, all the Nodes are represented as Objects. They have their own
properties and methods
 <Doctype html> is DocumentType Node
 <head> is an Element Node, so are meta, title, body, h1, p, ul and li
• Text contents like the title text 'This is a simple HTML document' is a text Node
• Some of the Nodes may have children. Like <ul> has <li> as children
• Body has <h1>, <p>,<ul> as children
DOM Node – Tree representation - Revisit
Navigation between nodes
There are some node properties to navigate between nodes:
 parentNode
 childNodes[node number]
 firstChild
 lastChild
 nextSibling
 previousSibling
Node creation - Example
// Creates a new em element
var newnode = document.createElement("em");
// To add text to the em element
var node = document.createTextNode("Text to add");
// Appending the text node to em element
newnode.appendChild(node);
// Appending new element to existing element
var elem = document.getElementById("p");
elem.appendChild(newnode);
Node Creation - Example
<body>
<p>Click the button to make a new Button element</p>
<button onclick="myFun()">Click</button>
<script>
function myFun() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("NewButton");
btn.appendChild(t);
document.body.appendChild(btn);
}
</script>
</body>
DOM Node - Methods
Method Description
appendChild() The appendChild() method will add new element as last child of parent , if we
want to insert before last child of parent then insertBefore() can be used.
Syntax :
parentElem.insertBefore(elem, nextSibling);
removeChild() Remove child node from parent node.
Syntax :
parentElem.removeChild(elem);
replaceChild() Replace the child element of parent Element, referenced by current Element
with the element.
Syntax :
parentElem.replaceChild(elem, currentElem);
DOM Node List
• The Node List object represents an ordered collection of nodes, indexed by number
(starting from zero).
• A Node List is not an array. For example the getElementsByTagName() method
returns a node list. The nodes can be accessed by an index number.
• The length property defines number of nodes in the list
var allParagraphs = document.getElementsByTagName("p");
var firstParagraph = allParagraphs[0];
Exercise
• Write a JavaScript function to manipulate an unordered list with multiple
following options:
 Create multiple lists
 Dynamically assign ID for each of the lists created
 In each of the lists created support the following operations:
 Insert (Before)
 Append
 Replace
 Remove
WebStack Academy
#83, Farah Towers,
1st Floor, MG Road,
Bangalore – 560001
M: +91-809555 7332
E: training@webstackacademy.com
WSA in Social Media:

More Related Content

What's hot

Ajax ppt
Ajax pptAjax ppt
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
Mindy McAdams
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv21
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
Bootstrap
BootstrapBootstrap
Bootstrap
Jadson Santos
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
www.netgains.org
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
Web controls
Web controlsWeb controls
Web controls
Sarthak Varshney
 
Css selectors
Css selectorsCss selectors
Css selectors
Parth Trivedi
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 

What's hot (20)

Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Web controls
Web controlsWeb controls
Web controls
 
Java script
Java scriptJava script
Java script
 
Css selectors
Css selectorsCss selectors
Css selectors
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 

Similar to JavaScript - Chapter 12 - Document Object Model

Part 7
Part 7Part 7
Part 7
NOHA AW
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
Lilia Sfaxi
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQueryLaila Buncab
 
J Query Public
J Query PublicJ Query Public
J Query Public
pradeepsilamkoti
 
lecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.pptlecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.ppt
ULADATZ
 
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdfUnit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
RAVALCHIRAG1
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
Muhammad Afzal Qureshi
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsRichie Rump
 
XML for beginners
XML for beginnersXML for beginners
XML for beginners
safysidhu
 
jQuery
jQueryjQuery
jQuery
Vishwa Mohan
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans Fabrizio Giudici
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
Karl-Henry Martinsson
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsMark Rackley
 
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
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
Fu Cheng
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
GOPAL BASAK
 

Similar to JavaScript - Chapter 12 - Document Object Model (20)

Part 7
Part 7Part 7
Part 7
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
J Query Public
J Query PublicJ Query Public
J Query Public
 
lecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.pptlecture 6 javascript event and event handling.ppt
lecture 6 javascript event and event handling.ppt
 
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdfUnit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
XML for beginners
XML for beginnersXML for beginners
XML for beginners
 
jQuery
jQueryjQuery
jQuery
 
Javascript
JavascriptJavascript
Javascript
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentials
 
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
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 

More from WebStackAcademy

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 

More from WebStackAcademy (20)

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 

JavaScript - Chapter 12 - Document Object Model

  • 3. What is DOM?  The Document Object Model (DOM) is a cross-platform and language-independent application programming interface.  The DOM, is the API through which JavaScript interacts with content within a website.  The DOM API is used to access, traverse and manipulate HTML and XML documents.  The DOM is a W3C (World Wide Web Consortium) standard.
  • 4. What is DOM Tree? • The DOM treats an HTML, XHTML, or XML document as a tree • structure • Each node is an object representing a part of the document • User case of HTML, XML and XHTML are different but DOM acts as a common standard
  • 5. HTML DOM Tree Objects
  • 6. Types of DOM nodes  Element nodes (HTML tag): Can have children / attributes.  Text nodes: Text nodes are contained within element nodes and cannot have child elements. Text nodes means all the text within nodes.  Attribute nodes (Attribute / Value pairs): Text / Attributes are children of element node, they cannot further have children or attributes
  • 7. DOM standards DOM level 0: • Earliest implementation of DOM • There existed no standard when its was implemented in some of the major browsers before 1998 DOM level 1 • It was recommended by W3C in 1998 • It will provide complete model for an entire HTML or XML document, to change any portion of the document DOM level 2 • It was published in 2000 by introducing additional features – getElementById, Event model, XML namespace (Avoiding name conflicts), Stylesheet
  • 8. DOM standards DOM level 0: • Earliest implementation of DOM • There existed no standard when its was implemented in some of the major browsers before 1998 DOM level 1 • It was recommended by W3C in 1998 • It will provide complete model for an entire HTML or XML document, to change any portion of the document DOM level 2 • It was published in 2000 by introducing additional features – getElementById, Event model, • XML namespace (Avoiding name conflicts), Stylesheet
  • 9. DOM standards DOM level 3 • It was published in 2004 • Added support for Xpath (Navigating between multiple nodes in XML) • Keyboard event handling DOM level 4 • It was published in 2015 • Latest version of DOM
  • 11. DOM methods • HTML DOM Methods are actions we can perform on HTML elements • HTML DOM Properties are values that we can set or change <script> document.getElementById("ex").innerHTML = "Hello World!"; </script> • getElementById -> Method • innerHTML -> Property
  • 12. DOM Methods getElementById() • Accesses any element on the page via its ID attribute • A fundamental method within the DOM for accessing elements on the page • This method will returns single element innerHTML • The innerHTML is used to get and replace the content of HTML elements.
  • 13. DOM Element getElementsByName(name) Returns an list with the given name attribute getElementsByTagName(name) Returns a list of elements with the given tag name. var allParagraphs = document.getElementsByTagName(“p”); var allParagraphs = document.getElementsByName(“number”);
  • 14. Element by class name getElementsByClassName() Returns a list of all elements with given class name var elements = document.getElementsByClassName(“example”);
  • 15. DOM Example <script> function GetById(){ document.getElementById("div1").innerHTML=document.getElementById("num").value; } function GetByName() { var nums= document.getElementsByName("number"); var res=''; for(var i=0; i<nums.length; i++) { res+=nums[i].value +"<br/>"; document.getElementById("div1").innerHTML= res; } } </script>
  • 16. DOM Example <body> <form id="form1"> <div> <input type="text" id="num" value="12345" /> <input type="text" name="number" value="num1" /> <input type="text" name="number" value="num2" /> <input type="text" name="number" value="num3" /> </div> <br /> <div id="div1" style="border-style: solid; border-width: thick; border-color: blue; width: 515px; height: 100px;"> Div Section </div> <br /> <input type="button" onclick="GetById();" value="Get Element By Id" /> <input type="button" onclick="GetByName();" value="Get Element By Name" /> </form> </body>
  • 17. Elements by CSS Selectors querySelector() Returns the first match of the passed selector string firstMatchElement = document.querySelector(“.example”); querySelectorAll() Returns a NodeList of DOM elements that match the query allMatchElements = document.querySelectorAll(“.example");
  • 18. Exercise • Write a JavaScript program to modify the text-align, font-size, font-family of heading1 using getElementById • Write a JavaScript program to change the background color of all the <div> tag • Write a JavaScript to add the text shadow in all paragraphs in the given essay Some useful tips: • <element-name>.style.textShadow = “Apx Bpx” will set you the shadow
  • 20. Documents • Web browser window is represented by window object • Every window has a document property that refers to document objects • The document objects represents the web page • We can access and manipulate HTML using document objects
  • 21. Changing HTML elements Methods Description EvalError Change the inner HTML of an HTML element RangeError Change the attribute value of an HTML element ReferenceError Changes the attribute value of an HTML element SyntaxError TypeError
  • 22. Adding and Deleting Element Methods Description document.createElement() Create an HTML Element document.removeChild() Remove an HTML Element document.appendChild() Add an HTML Element document.replaceChild() Replace an HTML Element document.write() Write into the HTML output stream document.insertBefore() Insert before an HTML element
  • 23. Adding Event Handlers Methods Description Document.getElementById(id).onclick = function() { // Code here… } Adding an event hander on mouse clicking
  • 24. HTML DOM – Handling images <html> <script> function imgFunc() { document.getElementById(“myimage").src = “jobsold.jpg"; } </script> <body> <img id=“myimage" src=“jobsyoung.jpg" width=500 height=200> <button onclick="imgFunc()">Click Here to change image</button> </body> </html>
  • 25. HTML DOM – Table manipulation • The Table object of the DOM supports dynamically generate a table or certain rows/columns • We can access a <table> element by using getElementbyId() Method Description createCaption() Creates an empty <caption> elements and adds it to the table deleteCaption() Removes the first caption element from the table insertRow() Inserts new row in the specific index deleteRow() Removes a row from the table insertCell() Inserts new column in the specific row createTHead() Creates an empty <thead> elements and adds it to the table deleteTHead() Removes the <thead> element from the table createTFoot() Creates an empty <tfoot> elements and adds it to the table deleteTFoot() Removes the <tfoot> element from the table
  • 26. www.webstackacademy.com HTML DOM – Table - Relationship view
  • 27. Exercise • Modify IPL table manipulation program with following options:  Taking user input for new row addition (instead of hard-coded value)  Adding new column in all rows called “City” and populate the city name the team belongs to  Add option to delete the column by taking the column index from the user  Insert table head as “IPL Team details” with appropriate column names (Name, Team, Captain etc..) Some useful tips: • <table-name>.rows.length will give you number of rows • <table-name>.rows[0].cells.length will give you number of columns
  • 29. JavaScript Animation • The JavaScript animation is implemented as gradual changing of DOM element styles or canvas objects • The whole process is split into pieces, and each piece is called by timer • An animation is created by replacing one Image frame with another at speed such that it appears to be a moving Image • Animations can be created using JavaScript by using a timer which replaces one image frame with another • The two timer function setTimeout() and setInterval() to execute JavaScript codes at set intervals
  • 30. DOM Animation Method Description setTimeout(function,duration) This function calls function after duration milliseconds from now setInterval(function,duration) This function calls function after every duration milliseconds clearTimeout(timeout) This function calls clears any timer set by the setTimeout() functions Some useful tips: • <element-name>.style.left = A px sets the left position of the element • <element-name>.style.right = A px sets the right position of the element • <element-name>.style.top = A px sets the top position of the element • <element-name>.style.bottom = A px sets the top position of the element
  • 31. Exercise • Write a JavaScript program to move two small squares inside one big square in a random manner. User should be able to start and stop this animation using button based events Some useful tips: Math.floor(Math.random() * Math.floor(max)) will give you a random number that is less than max value
  • 32. www.webstackacademy.com ‹#›www.webstackacademy.com Node & NodeList Handling DOM – Node Handling APIs
  • 33. DOM Nodes • In the context of DOM, every entity in an HTML or XML document, is referred as a Node • In JavaScript, all the Nodes are represented as Objects. They have their own properties and methods  <Doctype html> is DocumentType Node  <head> is an Element Node, so are meta, title, body, h1, p, ul and li • Text contents like the title text 'This is a simple HTML document' is a text Node • Some of the Nodes may have children. Like <ul> has <li> as children • Body has <h1>, <p>,<ul> as children
  • 34. DOM Node – Tree representation - Revisit
  • 35. Navigation between nodes There are some node properties to navigate between nodes:  parentNode  childNodes[node number]  firstChild  lastChild  nextSibling  previousSibling
  • 36. Node creation - Example // Creates a new em element var newnode = document.createElement("em"); // To add text to the em element var node = document.createTextNode("Text to add"); // Appending the text node to em element newnode.appendChild(node); // Appending new element to existing element var elem = document.getElementById("p"); elem.appendChild(newnode);
  • 37. Node Creation - Example <body> <p>Click the button to make a new Button element</p> <button onclick="myFun()">Click</button> <script> function myFun() { var btn = document.createElement("BUTTON"); var t = document.createTextNode("NewButton"); btn.appendChild(t); document.body.appendChild(btn); } </script> </body>
  • 38. DOM Node - Methods Method Description appendChild() The appendChild() method will add new element as last child of parent , if we want to insert before last child of parent then insertBefore() can be used. Syntax : parentElem.insertBefore(elem, nextSibling); removeChild() Remove child node from parent node. Syntax : parentElem.removeChild(elem); replaceChild() Replace the child element of parent Element, referenced by current Element with the element. Syntax : parentElem.replaceChild(elem, currentElem);
  • 39. DOM Node List • The Node List object represents an ordered collection of nodes, indexed by number (starting from zero). • A Node List is not an array. For example the getElementsByTagName() method returns a node list. The nodes can be accessed by an index number. • The length property defines number of nodes in the list var allParagraphs = document.getElementsByTagName("p"); var firstParagraph = allParagraphs[0];
  • 40. Exercise • Write a JavaScript function to manipulate an unordered list with multiple following options:  Create multiple lists  Dynamically assign ID for each of the lists created  In each of the lists created support the following operations:  Insert (Before)  Append  Replace  Remove
  • 41. WebStack Academy #83, Farah Towers, 1st Floor, MG Road, Bangalore – 560001 M: +91-809555 7332 E: training@webstackacademy.com WSA in Social Media: