KEMBAR78
lecture 6 javascript event and event handling.ppt
The JavaScript Language
1
CP 221: Internet programming and
applications I
(CIVE)
Objectives
• Learn about JavaScript
• Using JavaScript in HTML
• Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects
• Exception handling.
2
About JavaScript
• JavaScript was designed to add interactivity to HTML
pages
• JavaScript is a scripting language (a scripting language is
a lightweight programming language)
• A JavaScript consists of lines of executable computer
code
• JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a license
3
When not to use JavaScript
• When you need to access other resources.
– Files
– Programs
– Databases
• When you are using sensitive or copyrighted data or
algorithms.
– Your JavaScript code is open to the public.
4
Dealing with old browsers
• Some old browsers do not recognize script tags
• These browsers will ignore the script tags but will display the
included JavaScript
• To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
• The <!-- introduces an HTML comment
• To get JavaScript to ignore the HTML close comment, -->, the //
starts a JavaScript comment, which extends to the end of the line
5
Objects in JavaScript
• Objects have attributes and methods.
• Many pre-defined objects and object types.
• Using objects follows the syntax of C++/Java:
objectname.attributename
objectname.methodname()
• JavaScript is not Object Oriented – but Object-
Based
6
Three ways to create an object
• You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
• You can use new to create a “blank” object, and add fields
to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
• You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave"); 7
The document object
• Many attributes of the current document are available via the
document object:
Title Referrer
URL Images
Forms Links
Colors
8
document Methods
• document.write() like a print statement – the output
goes into the HTML document.
• document.writeln() adds a newline after printing.
• document.getElementById() Returns the element that
has the ID attribute with the specified value
document.write("My title is " +
document.title);
9
Example
<HEAD>
<TITLE>JavaScript is Javalicious</TITLE>
</HEAD>
<BODY>
<h3>I am a web page and here is my
name:</h3>
<script type=”text/Javascript”>
document.write(document.title);
</script>
<hr>
10
The navigator Object
• Represents the browser. Read-only!
• Attributes include:
appName
appVersion
platform
11
navigator Example
if (navigator.appName ==
"Microsoft Internet Explorer") {
document.writeln("<H1>This page
requires Netscape!</H1>");
}
12
The window Object
• Represents the current window.
• There are possible many objects of type Window, the
predefined object window represents the current window.
• Access to, and control of, a number of properties including
position and size.
13
window attributes
• document
• name
• status the status line
• parent
14
some window methods
alert()
close()
prompt()
moveTo() moveBy()
open()
scroll() scrollTo()
resizeBy()resizeTo()
15
The Math Object
• Access to mathematical functions and constants.
• Constants: Math.PI
• Methods:
Math.abs(), Math.sin(), Math.log(), Math.max(),
Math.pow(), Math.random(), Math.sqrt(), …
16
Math object in use
// returns an integer between 1 and 6
function roll() {
var x = Math.random();
// convert to range [0,6.0)
x = x * 6;
// add 1 and convert to int
return parseInt(1+x );
}
document.writeln("Roll is “ + roll() ); 17
Math object in use
<script type ="text/javascript">
<!--
var input1 = window.prompt("Enter first number", "0");
var input2 = window.prompt("Enter second number", "0");
var input3 = window.prompt("Enter third number", "0");
var value1 = parseFloat(input1);
var value2 = parseFloat(input2);
var value3 = parseFloat(input3);
var maxValue = maximum( value1, value2, value3);
document.writeln("First number: " + value1 +
"<br /> Second number: " + value2 +
"<br />Third number: " + value3 +
"<br />Maximum is: " +maxValue );
function maximum(x,y,z)
{
return Math.max(x,Math.max(y,z));
}
//-->
</script>
18
Array Objects
• Arrays are supported as objects.
• Attribute length
• Methods include:
concat join pop push reverse sort
19
Some similarity to C++
• Array indexes start at 0.
• Syntax for accessing an element is the same:
a[3]++;
blah[i] = i*72;
20
New Stuff (different from
C++)
• Arrays can grow dynamically – just add new elements at the
end.
• Arrays can have holes, elements that have no value.
• Array elements can be anything
• numbers, strings, or arrays!
21
Four ways to create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– var colors = new Array();
• You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more arguments
to create an array containing those values:
– var colors = new Array("red","green", "blue");
22
The length of an array
• If myArray is an array, its length is given by
myArray.length
• Array length can be changed by assignment beyond the
current length
• Example: var myArray = new Array(5); myArray[10] = 3;
• Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
• Example: myArray[50000] = 3; is perfectly OK
• But indices must be between 0 and 232-1
• As in C and Java, there are no two-dimensional arrays; but
you can have an array of arrays: board[3][3]
23
Arrays examples
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
• If you know the name of a property, you can use dot notation:
car.myCar
• If you don’t know the name of a property, but you have it in a
variable (or can compute it), you must use array notation:
car["my" + "Car"]
• var colors = [" blue ",
" green ",
" yellow "];
var x = window.prompt("enter a number ");
document.body.style.background = colors[x];
24
Array of Arrays Example
var board = [ [1,2,3],
[4,5,6],
[7,8,9] ];
for (i=0;i<3;i++)
for (j=0;j<3;j++)
board[i][j]++;
25
Array functions
• If myArray is an array,
– myArray.sort() sorts the array alphabetically
– myArray.sort(function(a, b) { return a - b; }) sorts numerically
– myArray.reverse() reverses the array elements
– myArray.push(…) adds any number of new elements to the end of
the array, and increases the array’s length
– myArray.pop() removes and returns the last element of the array,
and decrements the array’s length
– myArray.toString() returns a string containing the values of the
array elements, separated by commas
26
Passing Arrays to Functions
• To pass an array argument to a function, specify the name of
the array without brackets.
var a = [1,2,3,4,5];
outputArray(" Your array: ", a);
function outputArray(heading, theArray)
{
document.writeln(heading + theArray.join("
") + " <br /> ");
} 27
JavaScript HTML DOM
• With the HTML DOM, JavaScript can access and
change all the elements of an HTML document.
• The HTML DOM (Document Object Model)
• When a web page is loaded, the browser creates
a Document Object Model of the page.
• The HTML DOM model is constructed as a tree
of Objects:
12/3
The HTML DOM Tree of
Objects
12/3
The HTML DOM Tree of
Objects
12/3
• 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
What is the DOM?
• The DOM is a W3C (World Wide Web
Consortium) standard.
• The DOM defines a standard for accessing
documents:
• "The W3C Document Object Model (DOM) is a
platform and language-neutral interface that
allows programs and scripts to dynamically
access and update the content, structure, and
style of a document."
12/3
What is the DOM?
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
12/3
What is the HTML DOM?
• The HTML DOM is a standard object model and
programming interface for HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
• In other words: The HTML DOM is a standard for
how to get, change, add, or delete HTML
elements.
12/3
JavaScript - HTML DOM
Methods
• HTML DOM methods are actions you can perform (on HTML
Elements).
• HTML DOM properties are values (of HTML Elements) that
you can set or change.
• 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).
12/3
Example
The following example changes the content (the
innerHTML) of the <p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Hello World!";
</script>
</body>
</html>
12/3
Example..
• In the example above, getElementById is a method, while
innerHTML is a property.
12/3
The getElementById Method
• The most common way to access an HTML
element is to use the id of the element.
• In the example above the getElementById
method used id="demo" to find the element. 12/3
The innerHTML Property
• The easiest way to get the content of an element
is by using the innerHTML property.
• The innerHTML property is useful for getting or
replacing the content of HTML elements.
• The innerHTML property can be used to get or
change any HTML element, including <html> and
<body>
12/3
The HTML DOM Document
Object
• The document object represents your web page.
• 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.
12/3
The HTML DOM Document
Object
 Finding HTML Elements
12/3
Changing HTML Elements
12/3
JavaScript HTML DOM
Elements
How to find and access HTML
elements in an HTML page?
12/3
JavaScript HTML DOM
Elements
 Finding HTML Elements
• Often, with JavaScript, you want to manipulate HTML
elements.
• To do so, you have to find the elements first. There are several
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
12/3
JavaScript HTML DOM
Elements
 Finding HTML Element by Id
 The easiest way to find an HTML element in the DOM, is by
using the element id.
 This example finds the element with id="intro":
12/3
JavaScript HTML DOM
Elements
!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements by Id</h2>
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementsById</b>
method.</p>
<p id="demo"></p>
<script>
var myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script>
12/3
JavaScript HTML DOM
Elements
 If the element is found, the method will return the
element as an object (in myElement).
 If the element is not found, myElement will contain null.
12/3
JavaScript HTML DOM Elements(Finding HTML
Elements by Tag Name)
<!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements by Tag Name</h2>
<p>Hello World!</p>
<p>This example demonstrates the <b>getElementsByTagName</b>
method.</p>
<p id="demo"></p>
<script>
var x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The text in first paragraph (index 0) is: ' + x[0].innerHTML;
</script>
12/3
Changing HTML Content
• The easiest way to modify the content of an
HTML element is by using the innerHTML
property.
• To change the content of an HTML element, use
this syntax:
document.getElementById(id).innerHTML = new
HTML
• This example changes the content of a <p>
element:
12/3
Changing HTML Content
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML =
"New text!";
</script>
</body>
</html>
12/3
Changing the Value of an
Attribute
• To change the value of an HTML attribute, use this
syntax:
document.getElementById(id).attribute = new value
• This example changes the value of the src attribute of an
<img> element: 12/3
Changing the Value of an
Attribute
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
12/3
Changing HTML Style
• To change the style of an HTML element, use this
syntax:
document.getElementById(id).style.property =
new style
• The following example changes the style of a <p>
element:
12/3
Changing HTML Style
• <html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
12/3
Using Events
• The HTML DOM allows you to execute code when an event
occurs.
• Events are generated by the browser when "things happen" to
HTML elements:
 An element is clicked on
 The page has loaded
 Input fields are changed
• This example changes the style of the HTML element with
id="id1", when the user clicks a button:
12/3
Using Events
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
12/3
The End
56

lecture 6 javascript event and event handling.ppt

  • 1.
    The JavaScript Language 1 CP221: Internet programming and applications I (CIVE)
  • 2.
    Objectives • Learn aboutJavaScript • Using JavaScript in HTML • Language Elements • Variables • Operators • Control Statements • Functions • Objects • Exception handling. 2
  • 3.
    About JavaScript • JavaScriptwas designed to add interactivity to HTML pages • JavaScript is a scripting language (a scripting language is a lightweight programming language) • A JavaScript consists of lines of executable computer code • JavaScript is an interpreted language (means that scripts execute without preliminary compilation) • Everyone can use JavaScript without purchasing a license 3
  • 4.
    When not touse JavaScript • When you need to access other resources. – Files – Programs – Databases • When you are using sensitive or copyrighted data or algorithms. – Your JavaScript code is open to the public. 4
  • 5.
    Dealing with oldbrowsers • Some old browsers do not recognize script tags • These browsers will ignore the script tags but will display the included JavaScript • To get old browsers to ignore the whole thing, use: <script type="text/javascript"> <!-- document.write("Hello World!") //--> </script> • The <!-- introduces an HTML comment • To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment, which extends to the end of the line 5
  • 6.
    Objects in JavaScript •Objects have attributes and methods. • Many pre-defined objects and object types. • Using objects follows the syntax of C++/Java: objectname.attributename objectname.methodname() • JavaScript is not Object Oriented – but Object- Based 6
  • 7.
    Three ways tocreate an object • You can use an object literal: – var course = { number: "CIT597", teacher="Dr. Dave" } • You can use new to create a “blank” object, and add fields to it later: – var course = new Object(); course.number = "CIT597"; course.teacher = "Dr. Dave"; • You can write and use a constructor: – function Course(n, t) { // best placed in <head> this.number = n; this.teacher = t; } – var course = new Course("CIT597", "Dr. Dave"); 7
  • 8.
    The document object •Many attributes of the current document are available via the document object: Title Referrer URL Images Forms Links Colors 8
  • 9.
    document Methods • document.write()like a print statement – the output goes into the HTML document. • document.writeln() adds a newline after printing. • document.getElementById() Returns the element that has the ID attribute with the specified value document.write("My title is " + document.title); 9
  • 10.
    Example <HEAD> <TITLE>JavaScript is Javalicious</TITLE> </HEAD> <BODY> <h3>Iam a web page and here is my name:</h3> <script type=”text/Javascript”> document.write(document.title); </script> <hr> 10
  • 11.
    The navigator Object •Represents the browser. Read-only! • Attributes include: appName appVersion platform 11
  • 12.
    navigator Example if (navigator.appName== "Microsoft Internet Explorer") { document.writeln("<H1>This page requires Netscape!</H1>"); } 12
  • 13.
    The window Object •Represents the current window. • There are possible many objects of type Window, the predefined object window represents the current window. • Access to, and control of, a number of properties including position and size. 13
  • 14.
    window attributes • document •name • status the status line • parent 14
  • 15.
    some window methods alert() close() prompt() moveTo()moveBy() open() scroll() scrollTo() resizeBy()resizeTo() 15
  • 16.
    The Math Object •Access to mathematical functions and constants. • Constants: Math.PI • Methods: Math.abs(), Math.sin(), Math.log(), Math.max(), Math.pow(), Math.random(), Math.sqrt(), … 16
  • 17.
    Math object inuse // returns an integer between 1 and 6 function roll() { var x = Math.random(); // convert to range [0,6.0) x = x * 6; // add 1 and convert to int return parseInt(1+x ); } document.writeln("Roll is “ + roll() ); 17
  • 18.
    Math object inuse <script type ="text/javascript"> <!-- var input1 = window.prompt("Enter first number", "0"); var input2 = window.prompt("Enter second number", "0"); var input3 = window.prompt("Enter third number", "0"); var value1 = parseFloat(input1); var value2 = parseFloat(input2); var value3 = parseFloat(input3); var maxValue = maximum( value1, value2, value3); document.writeln("First number: " + value1 + "<br /> Second number: " + value2 + "<br />Third number: " + value3 + "<br />Maximum is: " +maxValue ); function maximum(x,y,z) { return Math.max(x,Math.max(y,z)); } //--> </script> 18
  • 19.
    Array Objects • Arraysare supported as objects. • Attribute length • Methods include: concat join pop push reverse sort 19
  • 20.
    Some similarity toC++ • Array indexes start at 0. • Syntax for accessing an element is the same: a[3]++; blah[i] = i*72; 20
  • 21.
    New Stuff (differentfrom C++) • Arrays can grow dynamically – just add new elements at the end. • Arrays can have holes, elements that have no value. • Array elements can be anything • numbers, strings, or arrays! 21
  • 22.
    Four ways tocreate an array • You can use an array literal: var colors = ["red", "green", "blue"]; • You can use new Array() to create an empty array: – var colors = new Array(); • You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; • You can use new Array(n) with a single numeric argument to create an array of that size – var colors = new Array(3); • You can use new Array(…) with two or more arguments to create an array containing those values: – var colors = new Array("red","green", "blue"); 22
  • 23.
    The length ofan array • If myArray is an array, its length is given by myArray.length • Array length can be changed by assignment beyond the current length • Example: var myArray = new Array(5); myArray[10] = 3; • Arrays are sparse, that is, space is only allocated for elements that have been assigned a value • Example: myArray[50000] = 3; is perfectly OK • But indices must be between 0 and 232-1 • As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: board[3][3] 23
  • 24.
    Arrays examples • car= { myCar: "Saturn", 7: "Mazda" } – car[7] is the same as car.7 – car.myCar is the same as car["myCar"] • If you know the name of a property, you can use dot notation: car.myCar • If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car["my" + "Car"] • var colors = [" blue ", " green ", " yellow "]; var x = window.prompt("enter a number "); document.body.style.background = colors[x]; 24
  • 25.
    Array of ArraysExample var board = [ [1,2,3], [4,5,6], [7,8,9] ]; for (i=0;i<3;i++) for (j=0;j<3;j++) board[i][j]++; 25
  • 26.
    Array functions • IfmyArray is an array, – myArray.sort() sorts the array alphabetically – myArray.sort(function(a, b) { return a - b; }) sorts numerically – myArray.reverse() reverses the array elements – myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length – myArray.pop() removes and returns the last element of the array, and decrements the array’s length – myArray.toString() returns a string containing the values of the array elements, separated by commas 26
  • 27.
    Passing Arrays toFunctions • To pass an array argument to a function, specify the name of the array without brackets. var a = [1,2,3,4,5]; outputArray(" Your array: ", a); function outputArray(heading, theArray) { document.writeln(heading + theArray.join(" ") + " <br /> "); } 27
  • 28.
    JavaScript HTML DOM •With the HTML DOM, JavaScript can access and change all the elements of an HTML document. • The HTML DOM (Document Object Model) • When a web page is loaded, the browser creates a Document Object Model of the page. • The HTML DOM model is constructed as a tree of Objects: 12/3
  • 29.
    The HTML DOMTree of Objects 12/3
  • 30.
    The HTML DOMTree of Objects 12/3 • 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
  • 31.
    What is theDOM? • The DOM is a W3C (World Wide Web Consortium) standard. • The DOM defines a standard for accessing documents: • "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." 12/3
  • 32.
    What is theDOM? 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 12/3
  • 33.
    What is theHTML DOM? • The HTML DOM is a standard object model and programming interface for HTML. It defines:  The HTML elements as objects  The properties of all HTML elements  The methods to access all HTML elements  The events for all HTML elements • In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements. 12/3
  • 34.
    JavaScript - HTMLDOM Methods • HTML DOM methods are actions you can perform (on HTML Elements). • HTML DOM properties are values (of HTML Elements) that you can set or change. • 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). 12/3
  • 35.
    Example The following examplechanges the content (the innerHTML) of the <p> element with id="demo": <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> 12/3
  • 36.
    Example.. • In theexample above, getElementById is a method, while innerHTML is a property. 12/3
  • 37.
    The getElementById Method •The most common way to access an HTML element is to use the id of the element. • In the example above the getElementById method used id="demo" to find the element. 12/3
  • 38.
    The innerHTML Property •The easiest way to get the content of an element is by using the innerHTML property. • The innerHTML property is useful for getting or replacing the content of HTML elements. • The innerHTML property can be used to get or change any HTML element, including <html> and <body> 12/3
  • 39.
    The HTML DOMDocument Object • The document object represents your web page. • 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. 12/3
  • 40.
    The HTML DOMDocument Object  Finding HTML Elements 12/3
  • 41.
  • 42.
    JavaScript HTML DOM Elements Howto find and access HTML elements in an HTML page? 12/3
  • 43.
    JavaScript HTML DOM Elements Finding HTML Elements • Often, with JavaScript, you want to manipulate HTML elements. • To do so, you have to find the elements first. There are several 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 12/3
  • 44.
    JavaScript HTML DOM Elements Finding HTML Element by Id  The easiest way to find an HTML element in the DOM, is by using the element id.  This example finds the element with id="intro": 12/3
  • 45.
    JavaScript HTML DOM Elements !DOCTYPEhtml> <html> <body> <h2>Finding HTML Elements by Id</h2> <p id="intro">Hello World!</p> <p>This example demonstrates the <b>getElementsById</b> method.</p> <p id="demo"></p> <script> var myElement = document.getElementById("intro"); document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + myElement.innerHTML; </script> 12/3
  • 46.
    JavaScript HTML DOM Elements If the element is found, the method will return the element as an object (in myElement).  If the element is not found, myElement will contain null. 12/3
  • 47.
    JavaScript HTML DOMElements(Finding HTML Elements by Tag Name) <!DOCTYPE html> <html> <body> <h2>Finding HTML Elements by Tag Name</h2> <p>Hello World!</p> <p>This example demonstrates the <b>getElementsByTagName</b> method.</p> <p id="demo"></p> <script> var x = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' + x[0].innerHTML; </script> 12/3
  • 48.
    Changing HTML Content •The easiest way to modify the content of an HTML element is by using the innerHTML property. • To change the content of an HTML element, use this syntax: document.getElementById(id).innerHTML = new HTML • This example changes the content of a <p> element: 12/3
  • 49.
    Changing HTML Content <html> <body> <pid="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> </body> </html> 12/3
  • 50.
    Changing the Valueof an Attribute • To change the value of an HTML attribute, use this syntax: document.getElementById(id).attribute = new value • This example changes the value of the src attribute of an <img> element: 12/3
  • 51.
    Changing the Valueof an Attribute <!DOCTYPE html> <html> <body> <img id="myImage" src="smiley.gif"> <script> document.getElementById("myImage").src = "landscape.jpg"; </script> </body> </html> 12/3
  • 52.
    Changing HTML Style •To change the style of an HTML element, use this syntax: document.getElementById(id).style.property = new style • The following example changes the style of a <p> element: 12/3
  • 53.
    Changing HTML Style •<html> <body> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; </script> <p>The paragraph above was changed by a script.</p> </body> </html> 12/3
  • 54.
    Using Events • TheHTML DOM allows you to execute code when an event occurs. • Events are generated by the browser when "things happen" to HTML elements:  An element is clicked on  The page has loaded  Input fields are changed • This example changes the style of the HTML element with id="id1", when the user clicks a button: 12/3
  • 55.
    Using Events <!DOCTYPE html> <html> <body> <h1id="id1">My Heading 1</h1> <button type="button" onclick="document.getElementById('id1').style.color = 'red'"> Click Me!</button> </body> </html> 12/3
  • 56.