0% found this document useful (0 votes)
26 views

Dom V2

The document describes the Document Object Model (DOM) and how it represents an HTML page as a tree structure in the browser. The DOM consists of four main types of nodes - the document node, element nodes, attribute nodes, and text nodes. JavaScript can access and modify the DOM tree by selecting nodes using methods like getElementById() and then changing attributes or content. Event handlers allow JavaScript code to run when certain events occur, like onclick.

Uploaded by

ki.to4757
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Dom V2

The document describes the Document Object Model (DOM) and how it represents an HTML page as a tree structure in the browser. The DOM consists of four main types of nodes - the document node, element nodes, attribute nodes, and text nodes. JavaScript can access and modify the DOM tree by selecting nodes using methods like getElementById() and then changing attributes or content. Event handlers allow JavaScript code to run when certain events occur, like onclick.

Uploaded by

ki.to4757
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

JavaScript & HTML

DOM
1301236 - WEB-BASED PROGRAMMING
What is Document Object Model
(DOM)?
When a webpage is loaded, the browser
creates a Document Object Model (DOM) of
the page.
The HTML DOM model is constructed as a tree
of Objects:
What is Document Object Model
(DOM)?
The Document Object Model (DOM) specifies how browsers should create a model of an HTML
page and how JavaScript can access and update the contents of a web page while it is in the
browser window.

DOM consists of four main types of nodes.


◦ The DOCUMENT node
◦ Element nodes
◦ Attributes nodes
◦ Text nodes
THE DOCUMENT NODE
At the top of the tree a document node is
added; it represents the entire page
When you access any element, attribute, or
text node, you navigate to it via the document
node.
The document node is the starting point for all
visits to the DOM tree.
ELEMENTS NODES
To access the DOM tree, you start by looking
for elements. Once you find the element you
want, then you can access its text and
attribute nodes if you want to.
ATTRIBUTE NODES
The opening tags of HTML elements can carry
attributes, and these are represented by
attribute nodes in the DOM tree.
Attribute nodes are not children of the
element thar carries them; they are part of
that element.
Once you access an element, there are specific
JavaScript methods and properties to read or
change that element's attributes.
TEXT NODES
Text nodes :
◦ Once you have accessed an element node, you
can then reach the text within that element.
◦ This is stored in its own text node. Text nodes
cannot have children.
◦ If an element contains text and another child
element, then the child element is not a child of
the text node but rather a child of the containing
element
Example of DOM Nodes
Accessing and updating the DOM tree
Accessing and updating the DOM tree involves two steps:
◦ Locate the node that represents the element you want to work with.
◦ Use its text content, child elements, and attributes.
Single node selection
METHODS THAT RETURN A SINGLE ELEMENT NODE:

◦ -getElementByld(‘id’)
◦ Selects an individual element given the value of its id attribute.
◦ The HTML must have an id attribute in order for it to be selectable.

◦ -getElementsByName(‘fname’)
◦ Get all elements with the name “fname”
◦ getElementsByName() returns a collection of elements with a specified name.
Document Object Model (DOM)
Since each tag in a page corresponds to a JavaScript DOM Object, JS code can talk to these
objects to examine elements' state:
◦ e.g. see whether a box is checked

we can change state:


◦ e.g. insert some new text into a div
◦ e.g. we can change styles
◦ e.g. make a paragraph red
JavaScript and HTML DOM
Each node has attributes and methods:
◦ all HTML attributes are accessible <html>

◦ content is accessible <body>


<p id="p1">Hello World!</p>
To change the content of an HTML element, <script>
use this syntax: document.getElementById("p1").innerHTML = "New text!";
◦ document.getElementById(id) </script>
.innerHTML = “new HTML”; </body>

The following example changes the content </html>


of a <p> element:
JavaScript
EVENT HANDLERS
JavaScript Event Handlers
Allows a JavaScript function to be executed when the user does something.
Examples:
◦ onmouseover - when the mouse is moved over an element
◦ onload - when the page is finished loading
◦ onclick - when the mouse clicks an object
◦ onchange - form element changes
◦ onsubmit - form submitted
◦ onmouseout - mouse exits
<input type="submit"
onmouseover="this.style.color='red'"

onmouseout="this.style.color='gray'" />

<input type="submit" onclick="validate_form()">


Example Alert on Click, Using External File
<head>
<script src="externalFunction.js">
</script>
</head>
<body>
<p onclick="start()" style="border: 2px solid red;">
If you click on this paragraph, then it will call an external script
function named "start" in the file named "externalFunction.js". Click
anywhere in this paragraph and you’ll get an alert.</p>

<p>Another paragraph, click and no alert.</p>


</body>

externalFunction.js: externalFunction.js must be in


function start() the same directory as the HTML file
{ that uses it, or the directory must be
alert ("Hello, glad you clicked!"); specified in the HTML file (src
} attribute).
Example: Modifying an image upon
clicking a button.
The following example alters the image when the button is clicked.
The window.onload event
There isis aa global
There global event
event called
called window.onload
window.onload event
event that
that occurs
occurs whenthe
whenthe page
page body
body isis done
done being
being
loaded
loaded
IfIf you
you attach
attach aa function
function as
as aa handler
handler for
for window.onload,
window.onload, itit will
will run
run at
at that
that time
time

function functionName()
function functionName() {{
// code
// code to
to initialize
initialize the
the page
page
...
...
}}

// run
// run this
this function
function once
once the
the page
page has
has finished
finished loading
loading
window.onload == functionName;
window.onload functionName; //you
//you shouldn't
shouldn't write
write ()() when
when attaching
attaching the
the handler
handler
Onmouseover, onmouseout and onload
Event Handler Example
The example below incorporates onmouseover and onmouseout effects into two buttons.
Onmouseover, onmouseout and onload
Event Handler Example
Another way to use onload event
onmouseover, onmouseout event
example#2
Onchange Event Handler Example
The example below adds onchange effects into a drop down list.
Onchange Event Handler Example
JavaScript
DEALING WITH FORM ELEMENTS
How to get the value of a text field
This example shows how to retrieve the value entered in the text field.
How to get the value of a text field
Getting value from radio button
This example shows how to obtain the value from radio buttons.
Getting value from radio button
Getting value from checkbox
This example shows how to obtain the value from checkbox buttons.
Getting value from checkbox
Using textarea input in JavaScript
Using textarea input in JavaScript
Converter to convert from Fahrenheit to
Celsius, using onclick and JS function
Converter to convert from Fahrenheit to
Celsius, using onclick and JS function
Form Validation Example
The following form validation example is to make sure email addresses are equal.
Form Validation Example
Getting selected value in dropdown list
Getting selected value in dropdown list
JavaScript
DATE OBJECT
JavaScript Date Object
Date objects are created with the new Date() constructor.
new Date() creates a date object with the current date and time.
Example:
Date Get Methods
Method Description
getFullYear() Get year as a four digit number
(yyyy)
getMonth() Get month as a number (0-11)
getDate() Get day as a number (1-31)
getDay() Get weekday as a number (0-6)
getHours() Get hour (0-23)
getMinutes() Get minute (0-59)
getSeconds() Get second (0-59)
getMilliseconds() Get millisecond (0-999)
getTime() Get time (milliseconds since
January 1, 1970)
Date Object Example
JavaScript
TIMING EVENTS
JavaScript Timing Events
JavaScript can be executed in time-intervals, this is called timing events.
The two key methods to use with JavaScript are:
setTimeout(function, Time in milliseconds)
Executes a function, after waiting a specified number of milliseconds.

setInterval(function, Time in milliseconds)


Same as setTimeout(), but repeats the execution of the function continuously.

The clearTimeout() method stops the execution of the function specified in setTimeout().
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
setTimeout() Method Example
setInterval() Method Example
JavaScript
STRINGS
Some of JavaScript String Methods
length concat()

substring() trim()

substr() charAt()

toUpperCase() charCodeAt()

toLowerCase() split()

indexOf() lastIndexOf()
Extracting String Parts

substring(start, end): extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position (end not included).
If you omit the second parameter, the method will slice out the rest of the string
substr(start, length): is similar to substring, the difference is that the second parameter
specifies the length of the extracted part.
Example Extracting String Parts

<html>
<body>
<h1>JavaScript String Methods</h1>
<p id="str"></p>
<script>
var str = "Good Morning!";
document.getElementById("str").innerHTML = str.substring(0,6);
</script>
</body>
</html>
Converting to Upper Case
A string is converted to upper case with toUpperCase().
A string is converted to lower case with toLowerCase().
The length property returns the length of a string.
Example Converting to Upper
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="greeting">Convert string to upper case</p>
<script>
function myFunction()
{
var text = document.getElementById("greeting").innerHTML;
document.getElementById("greeting").innerHTML = text.toUpperCase();
}
</script>
</body>
</html>
JavaScript String concat()

concat() joins two or more strings.


The concat() method can be used instead of the plus operator. These two lines do the same:
Example:

var text = "Hello" + " " + "World!";


text = "Hello".concat(" ", "World!");
String Methods
charAt(position):
The charAt() method returns the character at a specified index (position) in a string
◦ Example:
var text = "HELLO WORLD";
var ch = text.charAt(0);

The charCodeAt() method returns the unicode of the character at a specified index in a string.
Example:
<script>

var s = "ZEBRA";

var s2 = "AbCdEfG";

document.writeln( "<p>Character at index 0 in '" + s + "' is " + s.charAt( 0 ) );

document.writeln( "<br >Character code at index 0 in '"+ s + "' is " + s.charCodeAt( 0 ) + "</p>" );

document.writeln( "<p>'" + s2 + "' in lowercase is '" + s2.toLowerCase() + "'" );

document.writeln( "<br >'" + s2 + "' in uppercase is '" + s2.toUpperCase() + "'</p>" );

for(var i=0;i<s.length;i++)

document.writeln( "<br >"+ s.charAt(i));

document.writeln("<br > length="+s.length+"<br />");

</script>
More String Methods
A string can be converted to an array with the split() method.
The trim() method removes whitespace from both sides of a string.
The indexOf() method returns the index (position) the first occurrence of a string in a string. If
a substring is NOT found, then indexOf() will return -1
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string

You might also like