Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Lec 8 Basic JavaScript DOM Client Side Validation 03052023 122614pm

CS Lecture

Uploaded by

sumera sajid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lec 8 Basic JavaScript DOM Client Side Validation 03052023 122614pm

CS Lecture

Uploaded by

sumera sajid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Web Engineering

DEPARTMENT OF COMPUTER SCIENCE


BAHRIA UNIVERSITY, ISL AMABAD
References
These slides have been modified from the slides prepared by Mr. Ali
Irfan and Ms. Rafia Hasan (among others) and include additional
material from
◦ www.w3schools.com
◦ JavaScript: The Definitive Guide, 8th Edition, David Flanagan. O'Reilly
Media. 2014
Agenda Item

• JavaScript – Working with DOM


INTRODUCTION
DOM stands for “Document Object Model”.
The DOM is a W3C (World Wide Web Consortium) standard for accessing documents.
It defines the logical structure of documents and the way a document is accessed and manipulated.
The DOM connects web pages to scripts or programming languages.
The DOM is designed to be used with any programming language.

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.
DOM SPECIFICATION

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
DOM VERSIONS
DOM Level 2 DOM Level 3 DOM Level 4
DOM Level 1

Provided a Published in late


complete model 2000. It
for an entire introduced the Published in April 2004
“getElementById added support for Published in
HTML or XML
” function as well XPath and 2015.
document,
as an event keyboard event It is a snapshot
including the
model and handling, as well as an of the
means to change
support for XML interface WHATWG
any portion of
namespaces and for serializing documents living
the document.
CSS. as XML. standard.
What is DOM?

Standard object model & programming interface to HTML


• An HTML element is an object (e.g. <p>, <div>)
• DOM defines properties for HTML element object (e.g. <p>.id)
• Methods to access HTML elements
• Events for HTML elements (after obtaining object in JS)
• The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
JavaScript HTML DOM

With the HTML DOM, JavaScript can access


and change all the elements of an HTML
document.

When a web page is loaded, the browser


creates a Document Object Model of a page.

The HTML DOM model is constructed as a tree


of Objects:
JavaScript HTML DOM
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
JavaScript - HTML DOM
methods
The DOM Programming Interface

• The HTML DOM can be accessed with JavaScript (and with other
programming languages).

• In the DOM, all HTML elements are defined as objects.

• The programming interface is the properties and methods of each


object.

A property is a value that you can get or set (like changing the content
of an HTML element).
A method is an action you can do (like add or deleting an HTML
element).
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
Access Elements
JavaScript offers 3 methods to find/access HTML elements

• document.getElementById(id)
• Access a unique element based on id

• document.getElementsByTagName(name)
• Access all elements with specific tag

• document.getElementsByClassName(name)
• Access all elements with specific class applied
FINDING HTML ELEMENTS BY TAG NAME

Returns an array of elements with the given tag name. The example given below finds all <p> elements.
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
FINDING HTML ELEMENTS BY CLASS NAME

If you want to find all HTML elements with the same class name, use
getElementsByClassName().

Returns an array of elements with the given class attribute.

This example returns a list of all elements with class="intro".


Accessing value of elements
You can access the “value” of an element by the value property.
For example, if you have an “input” element that has the attribute id=“dem” :

var pass = document.getElementById(‘dem').value;


Change Elements
There are multiple ways to change attributes/content of element

• [htmlElementObject].innerHTML = “<p>Hello!<br/>How are you ?</p>”


• Translates HTML elements and render accordingly

Hello!
How are you?

• [htmlElementObject].innerText = “<p>Hello!<br/>How are you?</p>”


• Doesn’t translate HTML elements and render as text

<p>Hello!<br/>How are you?</p>


Change Elements

• [htmlElementObject].[attribute] = [value]
• document.getElementById(“dvTitle”).className = “newClass”

• [htmlElementObject].setAttribute(attribute, value)
• document.getElementById(“dvTitle”).setAttribute(“class”, “newClass”)

• [htmlElementObject].style.[property] = [value]
• document.getElementById(“dvTitle”).style.color = “red”
ADDING AND DELETING ELEMENTS
Important Functions

• Date() to get current date (client’s machine)

• setInterval(), continue to execute function/code after specified time until explicitly


stopped
• setInterval(move, 10) //execute function move after every 10 milliseconds

• clearInterval(), used to stop execution of setInterval()

• setTimeout, used to execute function/code only once after specified time


• setTimeoutl(move, 3000) //execute function move once after 3 seconds
ADDING EVENTS HANDLERS

Finding HTML Objects


• The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections,
and properties.
• These are still valid in HTML5.
• Later, in HTML DOM Level 3, more objects, collections, and properties were added.

https://www.w3schools.com/js/js_htmldom_document.asp
JAVASCRIPT HTML DOM EVENTS

HTML DOM allows JavaScript to react to HTML events.


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:
the content of the <h1>
element is changed
when a user clicks on it:
HTML DOM Events
HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document.
Events are normally used in combination with functions, and the function will not be executed before the
event occurs (such as when a user clicks a button).
The event model was standardized by the W3C in DOM Level 2.

Mouse Events Form Events Print Events


Keyboard Events Drag Events Media Events
Frame/Object Events Clipboard Events Touch Events
Transition Events Server-Sent Events Misc Events
Animation Events
ASSIGN EVENTS USING THE HTML DOM

The HTML DOM allows you to assign events to


HTML elements using JavaScript.

In the example shown, a function


named displayDate is assigned to an HTML
element with the id="myBtn".

The function will be executed when the button is


clicked.
• In the example above, a function named displayDate is
assigned to an HTML element with the id="myBtn”.

• The function will be executed when the button is


clicked.
READING ASSIGNMENT
Finding HTML elements by CSS selectors

JavaScript HTML DOM EventListener

Browser Object Model


DOM TREE & NODES
According to the W3C HTML DOM standard, everything in an HTML
document is a node.

With the HTML DOM, you can navigate the node tree using node relationships.

1. The entire document is a document node


2. Every HTML element is an element node
3. The text inside HTML elements are text nodes
4. Every HTML attribute is an attribute node
5. All comments are comment nodes
TYPESOF NODE
A DOM-tree comprises the following types of nodes:

Document Node: the root node representing the entire HTML document.
Element node: represents an HTML element (or tag). An element node may have child nodes,
which can be either element or text node. Element node may also have attributes.
Text Node: contains the text content of an element.
Others: such as comment, attribute.
Node Relationships
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.
•In a node tree, the top node is
called the root (or root node)
•Every node has exactly one
parent, except the root (which
has no parent)
With the HTML DOM, all nodes in the node tree can •A node can have a number of
be accessed by JavaScript. New nodes can be children
created, and all nodes can be modified or deleted. •Siblings (brothers or sisters)
are nodes with the same parent
DOM NODE PROPERTIES
1. nodeName: contain the name of the node, which is 3. nodeValue: contain the value of the node.
read-only.
◦ nodeValue for Text node is the
◦ The nodeName for an Element node is text contained;
the tag-name; ◦ nodeValue for Element node is
◦ nodeName for the Document node undefined.
is #document;
4. parentNode: reference to parent node. There
◦ nodeName for Text nodes is #text. is only one parent node in a tree structure.

2. nodeType: an integer indicating the type of the node,


5. childNodes: array (or node-list) of child
e.g. nodes.
6. firstChild, lastChild: reference to the first and
◦ Element (1) last child node.
◦ Attribute (2) 7. prevSibling, nextSibling: reference to the
◦ Text (3) previous and next sibling in the same level.
NAVIGATING BETWEEN NODES

You can use the following node properties to navigate between nodes with JavaScript:

parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
CHILD NODES AND NODE
VALUES
A common error in DOM processing is to expect an element node to contain text.

The element node <title> (in the example above) does not contain text.
It contains a text node with the value "DOM Tutorial".
CHILD NODES AND NODE
TheVALUES
value of the text node can be accessed by the node’s innerHTML property:

Accessing the innerHTML property is the same as accessing the nodeValue of the first child:

Accessing the first child can also be done like this:


All examples retrieve
the text of an <h1>
element and copies it
into a <p> element.
DOM ROOT NODES

There are two special properties that allow access to the full document:

document.body - The body of the document

document.documentElement - The full document returns the Element that is the root element of the
document.
document.body
◦ The body property sets or returns the
document's body.

On return, this property returns


the <body> element of the current document.

On set, this property overwrites all child


elements inside the existing <body> element,
and replaces it with the new, specified
content.
document.body
document.documentElement
THE nodeName PROPERTY
Note: nodeName always
contains the uppercase tag
name of an HTML
element.
THE nodeType PROPERTY
THE nodeType PROPERTY
EXAMPLE
Get the node name, node
value and the node type of the
<div> element's first child
node:
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.
CREATING NEW HTML ELEMENTS - insertBefore()
• The insertBefore() method inserts a node as a child, right before an existing child,
which you specify.
EXAMPLE
EXAMPLE
REPALCING THE NODE
The replaceChild() method replaces a
child node with a new node.

The new node could be an existing node


in the document, or you can create a
new node.
EXAMPLE
Replace a text node in a <li> element in a list with a new text node:
THE HTMLCOLLECTION OBJECT

The getElementsByTagName() method returns an HTMLCollection object.


An HTMLCollection object is an array-like list (collection) of HTML elements.
The elements in the collection can be accessed by an index number.
The index starts at 0.
EXAMPLE
The following code selects all <p> elements in a document:
HTMLCollection Length
The length property defines the number of elements in an HTMLCollection:

This example creates a collection of all <p> elements. Then displays the length of the collection.

An HTMLCollection is NOT an array!

HTMLCollection may look like an array, but it is not. You can loop through the list and
refer to the elements with a number (just like an array).However, you cannot use
array methods like valueOf(), pop(), push(), or join() on an HTMLCollection.
JavaScript Events
Mouse Events

• onmouseenter
• onmouseleave
• onmouseover
• onmouseout
• onmousemove
• Many more……..
JavaScript Events
Input events
◦ onsubmit - When a user clicks the submit button
◦ onblur - When a user leaves an input field
◦ onchange - When a user changes the content of an input field
◦ onchange - When a user selects a dropdown value
◦ onfocus - When an input field gets focus
◦ onselect - When input text is selected
◦ onreset - When a user clicks the reset button
◦ onkeydown - When a user is pressing/holding down a key
◦ onkeypress - When a user is pressing/holding down a key
◦ onkeyup - When the user releases a key
JavaScript Events (contd.)
Click Events
◦ onclick - When button is clicked
◦ ondblclick - When a text is double-clicked

Load Events
◦ onload - When the page has been loaded
◦ onload - When an image has been loaded
◦ onerror - When an error occurs when loading an image
◦ onunload - When the browser closes the document
◦ onresize - When the browser window is resized
What is BOM?
Browser Object Model, used to talk to browser

• window object is used to access browser properties

• document object is also property of window object.

• There are numerous properties available;


Further learning
Learn more about Client Side Scripting and DOM
◦ In the lab!

You might also like