Professional Documents
Culture Documents
5248 26042020074047 IV Unit Javascript HTML Dom Document
5248 26042020074047 IV Unit Javascript HTML Dom Document
If you want to access any element 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.
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object
collections, and properties. These are still valid in HTML5.
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
Typically you want to access an element within the DOM directly and
try to do something with it. Javascript provides a
document.getElementById() method, which is the easiest way to access
an element from the DOM tree structure. It will return the element that
has the ID attribute with the specified value.
document.getElementById("ID");
example:
<!DOCTYPE html>
<html>
<body>
function changeIt() {
alert(document.getElementById("heading").innerHTML);
</script>
</body>
</html>
2)getElementsByTagName
document.getElementsByTagName("TagName");
example:
<!DOCTYPE html>
<html>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<button onclick="count()">Get Value</button>
<script>
function count() {
alert(cnt.length);
</script>
</body>
</html>
3) getElementsByClassName()
The getElementsByClass() method works same like
getElementById() method, and it will returns a collection
of all elements in the document with the specified class
name.
document.getElementsByClassName("ClassName");
example:
<!DOCTYPE html>
<html>
<body>
<p class="testClass">Paragraph 1</p>
<p class="testClass">Paragraph 2</p>
<p class="testClass">Paragraph 3</p>
<p class="testClass">Paragraph 4</p>
<button onclick="count()">Change Value</button>
<script>
function count() {
var tmpClass =
document.getElementsByClassName("testClass");
alert(tmpClass.length);
tmpClass[1].innerHTML ="Second Paragraph";
}
</script>
</body>
</html>
4) querySelector()
It will returns the first element that matches a specified CSS selector in
the document.
<!DOCTYPE html>
<html>
<body>
<p id="testQuery">Paragraph 1</p>
<p id="testQuery">Paragraph 2</p>
<p id="testQuery">Paragraph 3</p>
<p id="testQuery">Paragraph 4</p>
<button onclick="change()">Change Value</button>
<script>
function change() {
document.querySelector("#testQuery").innerHTML ="First
Paragraph";
}
</script>
</body>
</html>
5)querySelectorAll()
<html>
<body>
<script>
function change() {
</script>
</body>
</html>
JavaScript - Events
What is an Event ?
When the page loads, it is called an event. When the user clicks a button,
that click too is an event. Other examples include events like pressing
any key, closing a window, resizing a window, etc.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
This is the most frequently used event type which occurs when a user
clicks the left button of his mouse. You can put your validation, warning
etc., against this event type.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value =
"Say Hello" />
</form>
</body>
</html>
onsubmit is an event that occurs when you try to submit a form. You
can put your form validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling
a validate() function before submitting a form data to the webserver. If
validate() function returns true, the form will be submitted, otherwise it
will not submit the data.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return
validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
These two event types will help you create nice effects with images or
even with text as well. The onmouseover event triggers when you bring
your mouse over any element and the onmouseout triggers when you
move your mouse out from that element. Try the following example.
Live Demo
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the
result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
// load.js
// An example to illustrate the load event
function load_greeting () {
alert("You are visiting the home page of \n" +
"Pete's Pickled Peppers \n" + "WELCOME!!!");
}
Example
var x = document.getElementById("myBtn");
<!DOCTYPE html>
<html>
<body>
<p>Click the "Try it" button to create a BUTTON element with a "Click
me" text.</p>
<script>
function myFunction() {
var x = document.createElement("BUTTON");
x.appendChild(t);
document.body.appendChild(x);
</script>
</body>
</html>
Button Object Properties
Property Description
Sets or returns whether a button should automatically get focus when the page
autofocus
loads, or not
formNoValidate Sets or returns whether the form-data should be validated or not, on submission
The Input Text object represents an HTML <input> element with type="text".
Example
var x = document.getElementById("myText");
<!DOCTYPE html>
<html>
<body>
<p>Click the "Try it" button to get the text in the text field.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Input Password Object
The Input Password object represents an HTML <input> element with type="password".
Example
var x = document.getElementById("myPsw");
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myPsw").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Overview of the DOM Level 2 Event Model
UI Logical events
Mutation events
Events caused by any action which modifies the structure of the
document.
Capturing
Bubbling
Cancelable
<input type = //
"reset" />; *********************************
<input type = ************************* //
"submit" id = // The event handler function for
"submitButton" />; the phone number text box
</p>;
</form>; function chkPhone(event) {
<script type =
"text/javascript" src // Get the target node of the
= "validator2r.js" >; event
</script>;
var myPhone =
</body>; event.currentTarget;
</html>;
// Test the format of the input
phone number
// validator2r.js
// The last part of var pos =
validator2. Registers myPhone.value.search(/^\d{3}-\d{3
the
// event handlers
// Note: This script
does not work with IE8
phoneNode.addEventList
ener("change",
chkPhone, false);
NAVIGATOR OBJECT
Navigator Object
DOM manipulating
DOM manipulation includes creating, inserting, copying,
removing, of DOM structure. All of these methods are
referred to as “setters,” as they change the DOM structure.
A few methods like .attr(), .html(), and .val() are also act as
“getters,” retrieving information from DOM elements for
later use.
jQuery Manipulating – Inserting
jQuery provides following methods that allow us to inserting
elements in the DOM
Element Positioning
o Absolute Positioning
o <p style = "position: absolute;
o left: 50px; top: 100px;">
<!-- absPos.html
An example to illustrate absolute Positioning of elements
-->
<html>
<head>
<title>
Absolute Positioning of elements
</title>
<style type = "text/css">
/* A style for a paragraph of text */
</style>
</head>
<body>
<p class="regtext">
The Snowy Owl (<i>Nyctea scandiaca</i>) is a bird of the Order Strigiformes.
It has a length of 20-27 in and a wingspan: 4.5-5 feet. Weight is 3.5-4.5
pounds.
Its Range is the Circumpolar; arctic regions of the old and new worlds.
Predatory feeder: eats small mammals, especially lemmings, birds,
fish and small marine mammals. Largely diurnal. Migrates to
southern Canada and the United States during years of lemming and
hare scarcity.
Breeds May-June, lays 2-14 eggs, number dependent upon the food
supply, at approximately 2-day intervals. Nest is scraped out of
the earth amid tall moss. The female incubates while the male
brings her food. Eggs hatch in 32-34 days. Young are covered in
white down. Fledging period between 50-55 days. Both parents feed
and tend the young, and are fiercely protective.
</p>
</body>
</html>
Relative Positioning
If no top and left properties are specified, the
element is placed exactly where it would have
been placed if no position property were given
But it can be moved later
If top and left properties are given, they are
offsets from where it would have placed without
the position property being specified
If negative values are given for top and left, the
displacement is upward and to the left
Can make superscripts and subscripts
<!-- absPos.html
Illustrates relative Positioning of elements
-->
<html>
<head>
<title>
Relative Positioning of elements
</title>
</head>
<body>
<p>
SNOWY <span style ="position: relative; top:10px;
font-family: Times; font-size:48pt;
font-style: italic; color: red;">
OWL </span> (<i>Nyctea scandiaca</i>)
</p>
</body>
</html>
Static Positioning
1.The default value if position is not specified
<body>
<form action ="">
<p>
x coordinate:<input type= "text" id ="leftCoord" size ="5" />
<br />
y coordinate: <input type= "text" id ="topCoord" size ="5" />
<br />
<input type= "button" value = "Move it" onclick =
"moveIt('850volvo',
document.getElementById('topCoord').value,
document.getElementById('leftCoord').value)" />
</P>
</form>
<div id ="850volvo" style = "position: absolute; top: 115 px; left: 0;">
<img src= "../volvopictures/850.jpg" alt="(Picture of an 850 Volvo)" />
</div>
</body>
</html>
Element Visibility:
<!-- showHide.html
An example to illustrateng visibility control of elements
-->
<html>
<head>
<title>
Visibility Control
</title>
<script type = "text/javascript">
<!--
// The event handler function to toggle the visibility of the volvo
image
function flipImag() {
dom = document.getElementById("164volvo").style;
// Flip the visibility objective to whatever is not now
if (dom.visibility == "visible")
dom.visibility = "hidden";
else
dom.visibility = "visible";
}
//-->
</script>
</head>
<body>
<form action ="">
Background color:
o <input type = "text" size = "10"
o name = "background"
o onchange = "setColor('background',
o this.value)">
<!-- dynColors.html
-->
<html>
<head>
</title>
<!--
function setColor(where, newColor) {
if (where == "background" )
document.body.style.backgroundColor = newColor;
else
document.body.style.color = newColor;
}
//-->
</script>
</head>
<body>
font-size: 24pt;">
</p>
<form action="">
<p>
Background color:
<br />
Foreground color:
<br />
</p>
</form>
</body>
</html>
*Changing fonts
We can change the font properties of a link by
using the mouseover and mouseout events to
trigger a script that makes the changes
<!-- dynLink.html
Illustrates mic font styles and colors for links
-->
<html>
<head>
<title>
Dynamic fonts for links
</title>
<style type ="text/css">
.regText { font: Times; font-size:16pt;}
</style>
</head>
<body>
<p class ="regText">
The female
<a style = "color: blue;"
onmouseover = "this.style.color = 'red';
this.style.font = 'italic 16pt Times';"
onmouseout = "this.style.color = 'blue';
this.style.font = 'normal 16pt Times';" >
incubates </a>
while the male brings her food.
</p>
</body>
</html>
Dynamic Content
<!-- dynContent.html
An example to illustrate dynamic values
-->
<html>
<head>
<title> Dynamic values
</title>
function messages(adviceNumber){
document.getElementById("adviceBox").value =helpers[adviceNumber];
}
// ************************************************** //
//-->
</script>
</head>
<body>
Stacking Elements
<head>
<title>
Dynamic stacking of images
</title>
<script type = "text/javascript">
<!--
var oldTop = "v130";
//
// ************************************************** //
/* The event handler function to move the given element to the
top of the stack.
*/
function toTop(newTop){
/* Set the two DOM addresses, one for the old top
element and one for the new top element
*/
domTop = document.getElementById(oldTop).style;
domNew = document.getElementById(newTop).style;
domTop.zIndex = "0";
domNew.zIndex = "10";
oldTop = newTop;
}
// ************************************************** //
//-->
</script>
</head>
<body>
<p>
<img class = "auto1" id = "v130"
src="../volvopictures/130.jpg" width=500
alt="picture of a volvo 130"
onclick = "toTop('v130')" />
</p>
</body>
</html>
<head>
<title>
Dynamic the position of the cursor
</title>
<script type = "text/javascript">
<!--
//
// ************************************************** //
/* The event handler function to get and display the
coordinates of the cursor, both in an element and
on the screen
*/
function findIt(evnt){
document.getElementById("xcoord1").value = evnt.clientX;
document.getElementById("ycoord1").value = evnt.clientY;
document.getElementById("xcoord2").value = evnt.screenX;
document.getElementById("ycoord2").value = evnt.screenY;
}
// ************************************************** //
//-->
</script>
</head>
<p>
Whitin the Client area <br />
x:
<input type = "text" id = "xcoord1" size = "4" />
y:
<input type = "text" id = "ycoord1" size = "4" />
Relative to the origin of the screen coordinate system:
x:
<input type = "text" id = "xcoord2" size = "4" />
y:
<input type = "text" id = "ycoord2" size = "4" />
</p>
</form>
<img src="../volvopictures/444.jpg" width=500 alt="picture of a
volvo 444" />
</p>
</body>
</html>
<head>
<title>
eacting to the mouse click
</title>
<script type = "text/javascript">
<!--
//
// ************************************************** //
/* The event handler function to display a message */
function displayIt() {
document.getElementById("message").style.visibility = "visible";
function hideIt() {
document.getElementById("message").style.visibility = "hidden";
}
// ************************************************** //
//-->
</script>
</head>
<body>
<p>
</body>
</html>
Slow Movement of Elements
of the destination
<head>
<title>
Moving text
</title>
<script type = "text/javascript"
src = "moveTextfuns.js">
</script>
</head>
</body>
</html>
// *************************************************************
// A function to initialize the x and y coordinates
// of the current position of the text to be moved,
// and the call the mover function
function initText(){
dom = document.getElementById('theText').style;
var x = dom.left;
var y = dom.top;
x = x.match(/\d+/);
y = y.match(/\d+/);
moveText(x,y);
// *************************************************************
// A function to move the text from its original position to
// (finalx, finaly)
function moveText(x,y){
/* If the x coordinates are not equal, move a to finalx */
if (x != finalx)
if( x > finalx) x--;
else if(x < finalx) x++;
if (y != finaly)
if( y > finaly) y--;
else if(y < finaly) y++;
dom.left = x + "px";
dom.top = y + "px";
XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying
how to display it like HTML tags, which are used to display the data. XML is not going to
replace HTML in the near future, but it introduces new possibilities by adopting many successful
features of HTML.
There are three important characteristics of XML that make it useful in a variety of systems and
solutions −
XML is extensible − XML allows you to create your own self-descriptive tags, or
language, that suits your application.
XML carries the data, does not present it − XML allows you to store the data
irrespective of how it will be presented.
XML is a public standard − XML was developed by an organization called the World
Wide Web Consortium (W3C) and is available as an open standard.
XML Usage
XML can work behind the scene to simplify the creation of HTML documents for large
web sites.
XML can be used to exchange the information between organizations and systems.
XML can be used to store and arrange the data, which can customize your data handling
needs.
XML can easily be merged with style sheets to create almost any desired output.
Virtually, any type of data can be expressed as an XML document.
Anatomy of an XML:
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
The following diagram depicts the syntax rules to write different types of markup
and text in an XML document.
XML Declaration
Where version is the XML version and encoding specifies the character
encoding used in the document.
Syntax Rules for XML Declaration
The XML declaration is case sensitive and must begin with "<?
xml>" where "xml" is written in lower-case.
An HTTP protocol can override the value of encoding that you put
in the XML declaration.
Root Element − An XML document can have only one root element.
For example, following is not a correct XML document, because both
the x and y elements occur at the top level without a root element −
<x>...</x>
<y>...</y>
XML Attributes
<a b = x>....</a>
In the above syntax, the attribute value is not defined in quotation marks.
XML References
XML Text
Some characters are reserved by the XML syntax itself. Hence, they
cannot be used directly. To use them, some replacement-entities are
used, which are listed below −
Not Allowed Character Replacement Entity Character Description
NOTE: You cannot change the type of the root node or of nodes
with children.
7. To view the XML source of the document, on the View menu,
click Source. The sample output resembles the following:
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
text1
</book>
<!--Comment1-->
<book id="bk102">
<!--Comment2-->
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
</book>
</catalog>
8. To save the XML document, on the File menu, click Save. To exit
XML Notepad, on the File menu, click Exit.
XML – DTDs
The XML Document Type Declaration, commonly known as DTD, is a
way to describe XML language precisely. DTDs check vocabulary and
validity of the structure of XML documents against grammatical rules of
appropriate XML language.
Syntax
Internal DTD
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Several elements are declared here that make up the vocabulary of the
<name> document. <!ELEMENT name (#PCDATA)> defines the
element name to be of type "#PCDATA". Here #PCDATA means parse-
able text data.
External DTD
In external DTD elements are declared outside the XML file. They are
accessed by specifying the system attributes which may be either the
legal .dtd file or a valid URL. To refer it as external DTD, standalone
attribute in the XML declaration must be set as no. This means,
declaration includes information from the external source.
Syntax
Types
XML Schemas
What is an XML Schema?
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XSL
XSLT is a language for transforming XML documents.
HTML uses predefined tags. The meaning of, and how to display each
tag is well understood.
XML does not use predefined tags, and therefore the meaning of each
tag is not well understood.
With the CSS3 Paged Media Module, W3C has delivered a new
standard for document formatting. So, since 2013, CSS3 is proposed as
an XSL-FO replacement.
What is XSLT?
With XSLT you can add/remove elements and attributes to or from the
output file. You can also rearrange and sort elements, perform tests and
make decisions about which elements to hide and display, and a lot
more.
XML – Processors
When a software program reads an XML document and takes actions
accordingly, this is called processing the XML. Any program that can
read and process XML documents is known as an XML processor. An
XML processor reads the XML file and turns it into in-memory
structures that the rest of the program can access.
Types
Web services.
What is Web Service
A Web Service is can be defined by following ways:
WSDL dependent: SOAP uses WSDL and doesn't have any other
mechanism to discover the service.
Can use SOAP: RESTful web services can use SOAP web services as
the implementation.