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

Java PDF

1. A script is a series of instructions that a computer can follow to achieve a goal, such as calculating the cost of a name plaque. 2. To write a script, you first define the goal and then break it down into tasks and steps. Each step must then be coded in a programming language. 3. Computers approach tasks differently than humans, so instructions for a script must be written programmatically by breaking problems down into discrete steps. Computers create models of the world using data to represent real-world objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Java PDF

1. A script is a series of instructions that a computer can follow to achieve a goal, such as calculating the cost of a name plaque. 2. To write a script, you first define the goal and then break it down into tasks and steps. Each step must then be coded in a programming language. 3. Computers approach tasks differently than humans, so instructions for a script must be written programmatically by breaking problems down into discrete steps. Computers create models of the world using data to represent real-world objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

2/25/2018

JAVASCRIPT
Haider M. Habeeb

REFERENCES
• Jon Duckett. 2014. JavaScript and JQuery: Interactive Front-End Web
Development (1st ed.). Indianapolis, Indiana: John Wiley & Sons
Publishing

• Refsnes, H. and Refsnes, S. and Refsnes, K.J. and Refsnes, J.E. and
Henthorne, K.D. 2010. Learn JavaScript and Ajax with w3Schools.
Indianapolis, Indiana: Wiley Publishing

1
2/25/2018

COURSE OBJECTIVES
• How JavaScript can be used in browsers to make websites
more:
• interactive,
• interesting,
• and user-friendly.
• How can be made writing JavaScript a lot easier by using
jQuery.

REQUIREMENTS
• You will need to know how to build web pages using HTML
and CSS.
• No prior experience with programming is necessary.
• The only equipment you need to use this book are a
computer with a modern web browser installed, and your
favorite code editor, (e.g., Notepad, TextEdit. Sublime Text.
or Coda).

2
2/25/2018

WHAT ELSE

• Learning to program with JavaScript involves:

1. Understanding some basic programming concepts and the


terms that JavaScript programmers use to describe them.

2. Learning the language itself, and, like all languages, you need to
know its vocabulary and how to structure your sentences.

3. Becoming familiar with how it is applied by looking at examples


of how JavaScript is commonly used in websites today.

JAVASCRIPT

The ABC of Programming

3
2/25/2018

INTERACTIVE WEB PAGES

• JavaScript allows you to make Web pages more


interactive by accessing and modifying the content
and markup used in a Web page while it is being
viewed in the browser.

ACCESS CONTENT
• You can use JavaScript to select any element, attribute, or
text from an HTML page.
• For example:
• Select the text inside all of the <hl> elements on a page.
• Select any elements that have a class attribute with a
value of note.
• Find out what was entered into a text input whose id
attribute has a value of email.

4
2/25/2018

MODIFY CONTENT
• You can use JavaScript to add elements, attributes, and
text to the page, or remove them.
• For example:
• Add a paragraph of text after the first <hl> element.
• Change the value of class attributes to trigger new CSS
rules for those elements.
• Change the size or position of an <img> element.

PROGRAM RULES
• You can specify a set of steps for the browser to follow (like a recipe),
which allows it to access or change the content of a page.
• For example:
• A gallery script could check which image a user clicked on and
display a larger version of that image.
• A mortgage calculator could collect values from a form, perform a
calculation, and display repayments.
• An animation could check the dimensions of the browser window
and move an image to the bottom of the viewable area (also
known as the viewport).

5
2/25/2018

REACT TO EVENTS
• You can specify that a script should run when a specific event has
occurred. For example, it could be run when:
• A button is pressed
• A link is clicked (or tapped) on
• A cursor hovers over an element
• Information is added to a form
• An interval of time has passed
• A web page has finished loading

A QUICK REFRESHER
• HTML Element:
• An element consist of the opening and closing tags.
• There are a few empty elements with no content.
• Opening tags can carry attributes.
• Attributes have a name and value.
• The value is usually given in quotes.

6
2/25/2018

A QUICK REFRESHER

• CSS Rules:
• CSS uses rules to indicate how the content of elements should be displayed
in the browser.
• Each rule has a selector and declaration block.
• Each declaration has a property and a value.

ABC OF PROGRAMING LANGUAGE

A What is a script and how do I create one?

B How do computers fit in with the world around them?

C How do I write a script for a web page?

7
2/25/2018

A
• What is a script and how do I create one?
• A script is a series of instructions that a computer can follow to
achieve a goal.
• You could compare scripts to any of the following:
• RECIPES
• HANDBOOKS
• MANUALS

WRITING A SCRIPT

• To write a script, you need to first state


your goal and then list the tasks that need
to be completed in order to achieve it.

• Start with the big picture of what you


want to achieve, and break that down
into smaller steps.

8
2/25/2018

SOLVE PROBLEM

1: DEFINE THE GOAL


• First, you need to define the task you want to achieve. (think of a puzzle)

2: DESIGN THE SCRIPT


• To design a script you split the goal out into a series of tasks.

3: CODE EACH STEP


• Each of the steps needs to be written in a programming language that the
computer understands.

DESIGN THE SCRIPT: TASKS & STEPS

9
2/25/2018

FROM STEPS TO CODE

• Every step for every task shown in a flowchart needs to be written in a


language the computer can understand and follow.

• Vocabulary: The words that computers understand.

• Syntax: How you put those words together to create instructions computers
can follow.

EXAMPLE
• Calculates the cost of a name plaque.

10
2/25/2018

EXAMPLE
• Tasks that have to be performed in order to
achieve the goals:
1. The script is triggered when the button is
clicked.
2. It collects the name entered into the
form field.
3. It checks that the user has entered a
value.
4. If the user has not entered anything, a
message will appear telling them to
enter a name.
5. If a name has been entered, calculate
the cost of the sign by multiplying the
number of letters by the cost per letter.
6. Show how much the plaque costs.

SUMMARY

• What is a script and how do I create one?


1. A script is a series of instructions that the computer can follow in order to
achieve a goal.
2. Each time the script runs, it might only use a subset of all the instructions.
3. Computers approach tasks in a different way than humans, so your instructions
must let the computer solve the task programmatically.
4. To approach writing a script, break down your goal into a series of tasks and
then work out each step needed to complete that task (a flowchart can help).

11
2/25/2018

B
• How do computers fit in with the world around them?

MODEL

• Computers create models of the


world using data

• Here is a model of a hotel, along


with some model trees, model
people, and model cars. To a
human, it is clear what kind of real -
world object each one represents.

12
2/25/2018

MODEL
• A computer has no predefined concept of what a hotel or car is. It does not
know what they are used for. Your laptop or phone will not have a favorite
brand of car, nor will it know what star rating your hotel is.
• So how do we use computers to create hotel booking apps, or video games
where players can race a car?
• The answer: is that programmers create a very different kind of model,
especially for computers.
• Programmers make these models using data.
• the data is all the computer needs in order to follow the instructions you give
it to carry out its tasks.

OBJECTS & PROPERTIES

• If you could not see the picture of


the hotel and cars, the data in
the information boxes alone
would still tell you a lot about this
scene.

13
2/25/2018

OBJECTS & PROPERTIES


• OBJECTS (THINGS)
• In computer programming, each physical thing in the world can be
represented as an object.
• In our example, there is one instance of the hotel object, and two instances
of the car object.
• Each object can have its own:
• Properties
• Events
• Methods
• Together they create a working model of that object.

OBJECTS & PROPERTIES


• PROPERTIES (CHARACTERISTICS)
• Both of the cars share common characteristics.
• In fact, all cars have:
• a make,
• a color,
• engine size.
• You could even determine their current speed. Programmers call these
characteristics the properties of an object.

14
2/25/2018

OBJECTS & PROPERTIES


• PROPERTIES (CHARACTERISTICS)
• Each property has a name and a value.
• each of these name/value pairs tells you something about each individual
instance of the object.
• The most obvious property of this hotel is its name.
• The value for that property is Quay.
• You can tell the number of rooms the hotel has by looking at the value next
to the rooms property.

NAME/VALUE PAIRS
• The idea of name/value pairs is used in both HTML and CSS.
• In HTML:
• an attribute is like a property; different attributes have different names, and
each attribute can have a value.
• in CSS:
• you can change the color of a heading by creating a rule that gives the
color property a specific value.
• Name/value pairs are used a lot in programming.

15
2/25/2018

EXAMPLE
• HOTEL OBJECT
• The hotel object uses property
names and values to tell you
about this particular hotel’
• CAR OBJECTS
• The car objects both share the
same properties, but each one
has different values for those
properties.

EVENTS
• In the real world, people interact with objects. These interactions can
change the values of the properties in these objects.
• Example: The car has been designed to respond differently when the driver
interacts with each of the two different pedals:
• The accelerator makes the car go faster
• The brake slows it down

16
2/25/2018

EVENT MODEL

Listen React

Source: Events in JavaScript by kirupa

EVENT MODEL
• WHAT DOES AN EVENT DO?
• Programmers choose which events they respond to.
• When a specific event happens, that event can be used to trigger a specific
section of the code.
• Scripts often use different events to trigger different types of functionality.
• So a script will state which events the programmer wants to respond to, and
what part of the script should be run when each of those events occur.

17
2/25/2018

EVENT MODEL

Source: Web Programming Step by Step, 2nd Edition - Chapter 8: JavaScript

EVENT
• HOTEL OBJECT
• A hotel will regularly have
bookings for rooms.
• Each time a room is reserved,
an event called book can be
used to trigger code that will
increase the value of the
bookings property.
• Likewise, a cancel event can
trigger code that decreases
the value of the bookings
property.

18
2/25/2018

METHODS

• WHAT IS A METHOD?

• Method typically represents how people (or other things) interact with an
object in the real world.

• They are like questions and instructions that:


• Tell you something about that object (using information stored in its properties).

• Change the value of one or more of that object's properties.

METHODS

• WHAT DOES A METHOD DO?

• The code for a method can contain lots of instructions that together
represent one task.

• When you use a method, you do not always need to know how it achieves
its task; you just need to know how to ask the question and how to interpret
any answers it gives you.

19
2/25/2018

METHODS
• HOTEL OBJECT
• Hotels will commonly be asked if
any rooms are free.
• To answer this question, a
method can be written that
subtracts the number of
bookings from the total number
of rooms.
• Methods can also be used to
increase and decrease the
value of the bookings property
when rooms are booked or
cancelled.

METHODS
• CAR OBJECTS
• The value of the currentSpeed
property needs to go up and down
as the driver accelerates and
brakes.
• The code to increase or decrease
the value of the currentSpeed
property could be written in a
method, and that method could be
called changeSpeed ().

20
2/25/2018

PUTTING IT ALL TOGETHER

• Computers use data to create models of things in the real world.

• The events, methods, and properties of an object all relate to each other:

• Events can trigger methods, and methods can retrieve or update an object's
properties.

PUTTING IT ALL TOGETHER


• HOTEL OBJECT
1. When a reservation is made,
the book event fires.
2. The book event triggers the
makeBooki ng () method,
which increases the value of
the bookings property.
3. The value of the bookings
property is changed to
reflect how many rooms the
hotel has available.

21
2/25/2018

PUTTING IT ALL TOGETHER


• CAR OBJECTS
1. As a driver speeds up, the
accel erate event fires.
2. The accelerate event calls
the changeSpeed ()
method. which in turn
increases the value of the
currentSpeed property.
3. The value of the
currentSpeed property
reflects how fast the car is
traveling.

WEB BROWSERS & OBJECTS


• Web browsers are programs built using objects
• WINDOW OBJECT
• On the right-hand page you can see a model of a computer with a browser
open on the screen.
• The browser represents each window or tab using a window object.
• The location property of the window object will tell you the URL of the current
page.

22
2/25/2018

DOCUMENT
OBJECT

DOCUMENT OBJECT
• DOCUMENT OBJECT
• The current web page loaded into each window is modelled using a
document object.
• The title property of the document object tells you what is between the
opening <title> and closing </title> tag for that web page, and
• The Last Modified property of the document object tells you the date this
page was last updated.

23
2/25/2018

DOCUMENT OBJECT

• THE DOCUMENT OBJECT REPRESENTS AN HTML PAGE

• Using the document object, you can access and change what content
users see on the page and respond to how they interact with it.

• Like other objects that represent real-world things, the document object has:
• Properties

• Methods

• Events

DOCUMENT OBJECT
• PROPERTIES
• Properties describe characteristics of the current web page (such as the title of
the page).
• METHODS
• Methods perform tasks associated with the document currently loaded in the
browser (such as getting information from a specified element or adding new
content).
• EVENTS
• A user clicking or tapping on an element.

24
2/25/2018

DOCUMENT OBJECT

• The document object is just one of a set of objects that all major browsers
support.

• When the browser creates a model of a web page, it not only creates a
document object, but it also creates a new object for each element on the
page.

• Together these objects are described in the Document Object Model (DOM).

DOCUMENT OBJECT

25
2/25/2018

BROWSER &WEB PAGE

• HOW A BROWSER SEES A WEB PAGE


1. Receive a page as html code

2. Create a model of the page and store it in memory

3. Use a rendering engine to show the page on screen

• All major browsers use a JavaScript interpreter to translate your


instructions (in JavaScript) into instructions the computer can follow.

BROWSER &WEB PAGE

26
2/25/2018

BROWSER &WEB PAGE

BROWSER &WEB PAGE

27
2/25/2018

SUMMARY

• How do computers fit in with the world around them?


1. Computers creates models of the world using data.
2. The models using objects to represents physical things. Objects can have
properties, methods, and events.
3. Programmers can write code to say “When this event occurs, run that code”.
4. Web browsers use HTML markup to create a model of the web page.
5. To make web pages interactive, write code that uses the browser’s model of
the web page.

C
• How do I write a script for a Web page?
• First, you need to know how JS will fit together with the HTML and CSS
in your web pages.

28
2/25/2018

<HTML>

• CONTENT LAYER
• . html files

• This is where the content of the page lives. The


HTML gives the page structure and adds
semantics.

{CSS}

• PRESENTATION LAYER

• .css files
• The CSS enhances the HTML page with rules that
state how the HTML content is presented
(backgrounds, borders, box dimensions, colors,
fonts, etc.).

29
2/25/2018

JAVASCRIPT()

• BEHAVIOR LAYER

• .js files
• This is where we can change how the page
behaves, adding interactivity. We will aim to
keep as much of our JavaScript as possible in
separate files.

PROGRESSIVE ENHANCEMENT
• These three layers form the basis of a popular approach to building web
pages called progressive enhancement.

30
2/25/2018

CREATING A BASIC
JAVASCRIPT
• This example adds a greeting into
an HTML page. The greeting
changes depending on the time of
day.

LINKING HTML TO JS
• When you want to use
JavaScript with a web page,
you use the HTML <script>
element to tell the browser it
is coming across a script.
• Its src attribute tells people
where the JavaScript file is
stored.

31
2/25/2018

RESULT
• After applying CSS rules
• Please note: Internet Explorer
sometimes prevents
JavaScript running when you
open a page stored on your
hard drive. If this affects you,
please try Chrome, Firefox,
Opera, or Safari instead.

OBJECTS & METHODS


• How to use objects and methods?

32
2/25/2018

RUNNING JAVASCRIPT

• JavaScript
runs where it
is found in
the HTML.

SUMMARY

• How do I write a script for a Web page?


• It is best to keep JavaScript code in its own JavaScript file. JavaScript files are
text files (like HTML pages and CSS style sheets), but they have the . j s extension.

• The HTML <script> element is used in HTML pages to tell the browser to load the
JavaScript file (rather like the <link> element can be used to load a CSS file).

• If you view the source code of the page in the browser, the JavaScript will not
have changed the HTML, because the script works with the model of the web
page that the browser has created.

33
2/25/2018

34
3/6/2018

JAVASCRIPT
Haider M. Habeeb

JAVASCRIPT

Basic JavaScript Instructions

1
3/6/2018

OBJECTIVES

• Reading and writing JavaScript.

• You will also learn how to give a web browser instructions you want it to
follow.

STATEMENTS
• A script is a series of instructions that a computer can follow one-by-one.
• Each individual instruction or step is known as a statement.
• Statements should end with a semicolon.
• Examples:
var today= new Date();
greeting = 'Welcome';
document.write(greeting) ;
• Some statements are surrounded by curly braces;
• these are known as code blocks.
• The closing curly brace is not followed by a semicolon.

2
3/6/2018

COMMENTS
• You should write comments to explain what your code does.
• They help make your code easier to read and understand.
• This can help you and others who read your code.
• SINGLE-LINE COMMENTS
var today = new Date(); // Create a new date object
var hour Now = today.getHours(); II Find the current hour
• MULTI-LINE COMMENTS
I* This script displays a greeting to the user based upon the current time.
It is an example from JavaScript & jQuery book *I

VARIABLES

• WHAT IS A VARIABLE?
• A script will have to temporarily store the bits of information it needs to do its job.
It can store this data in variables.

• How to declare a variable?

3
3/6/2018

VARIABLES
• How to assign variable a value?

DATA TYPES
• Numeric data type
• String data type
• Boolean data type

4
3/6/2018

VARIABLES

• Using a variable to
store a string.

VARIABLES

• Using quotes inside a


string

5
3/6/2018

VARIABLES

• Using a variable
to store a
boolean

VARIABLES
• Shorthand for creating variables

6
3/6/2018

VARIABLES

• Rules for naming variables

• The name must begin with a letter, dollar sign ($),or an underscore (_). It must
not start with a number.

• The name can contain letters, numbers, dollar sign ($), or an underscore (_).
Note that you must not use a dash(-) or a period (.) in a variable name.

• You cannot use keywords or reserved words.


• Keywords are special words that tell the interpreter to do something.

VARIABLES

• Rules for naming variables

• All variables are case sensitive, so score and Score would be different
variable names, but it is bad practice to create two variables that have the
same name using different cases.

• Use a name that describes the kind of information that the variable stores.

• If your variable name is made up of more than one word, use a capital letter
for the first letter of every word after the first word. (Camel Case)

7
3/6/2018

ARRAYS
• An array is a special type of variable. It doesn't just store one value; it stores a
list of values.

EXPRESSIONS
• An expression evaluates into (results in) a single value. Broadly speaking
there are two types of expressions.
• Expressions that just assign a value to a variable

• Expressions that use two or more values to return a single value

8
3/6/2018

OPERATORS
• Expressions rely on things called operators; they allow programmers to create
a single value from one or more values.
• Assignment Operators
• Arithmetic Operators
• String Operators
• Comparison Operators
• Logical Operators

SUMMARY
• A script is made up of a series of statements. Each statement is like a step in a
recipe.
• Scripts contain very precise instructions. For example, you might specify that a value
must be remembered before creating a calculation using that value.
• Variables are used to temporarily store pieces of information used in the script.
• Arrays are special types of variables that store more than one piece of related
information.
• JavaScript distinguishes between numbers (0-9), strings (text), and Boolean values
(true or false).
• Expressions evaluate into a single value.
• Expressions rely on operators to calculate a value.

9
3/6/2018

10
''

JAVASCRIPT
Haider M. Habeeb

JAVASCRIPT

Functions, Methods & Objects


Part I

1
''

FUNCTIONS, METHODS & OBJECTS

• Complex scripts can run to hundreds (even thousands) of lines.

• Programmers use functions, methods, and objects to organize their code.

FUNCTIONS, METHODS & OBJECTS


• Functions & Methods
• Functions consist of a series of statements that have been grouped together
because they perform a specific task.
• A method is the same as a function, except methods are created inside (and
are part of) an object.
• Objects
• Programmers use objects to create models using data, and that objects are
made up of properties and methods.
• Built-in Objects
• The browser comes with a set of objects that act like a toolkit for creating
interactive web pages.

2
''

FUNCTION
• What is a function? • Calling a function

FUNCTION
• Decelerating function that needs information

3
''

FUNCTION
• Getting a single value out of a function

FUNCTION
• Getting multiple values out of a function

4
''

ANONYMOUS FUNCTIONS
& FUNCTION EXPRESSIONS
• Function Declaration • Function Expression
Anonymous Function

IIFE
• Immediately Invoked Function
Expressions (IIFE)
• The final parentheses (shown on
green) tell the interpreter to call
the function immediately.
• The grouping operators (shown
on pink) are parentheses there to
ensure the interpreter treats this
as an expression.

5
''

IIFE

• When to use anonymous functions and IIFEs?


• As an argument when a function is called (to calculate a value for that
function).

• To assign the value of a property to an object.

• In event handlers and listeners to perform a task when an event occurs.

• To prevent conflicts between two scripts that might use the same variable
names.

VARIABLE SCOPE
• Local Variables

• Global Variables

6
''

OBJECT
• What is an object?

• Objects group
together a set of
variables and
functions to create a
model of a
something you
would recognize
from the real world.

OBJECT

• In an object, variables and functions take on new names.

• Variables become known as properties.


• If a variable is part of an object, it is called a property.

• Functions become known as methods.


• If a function is part of an object, it is called a method.

7
''

REAL LIFE OBJECT

OBJECT
• var person = "John";
• var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
• Key/value pair
Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

8
''

OBJECT
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {
return this.firstName + “ “ + this.lastName;
}

OBJECT
• Object Definition
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue“
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

9
''

OBJECT
• Hotel Object:
• Key/value pairs

OBJECT
• Hotel object contains the following
key/value pairs:
• Variables have a name and can
assign them a value of a string,
number, or Boolean.
• Arrays have a name and a group of
values. (Each item in an array is a
name/value pair because it has an
index number and a value.)
• Named functions have a name and
value that is a set of statements to run
if the function is called.
• Objects consist of a set of name/value
pairs (but the names are referred to as
keys).

10
''

11
''

JAVASCRIPT
Haider M. Habeeb

JAVASCRIPT

Functions, Methods & Objects


Part II

1
''

OBJECT

• There are two ways for creating Object:


1. Literal Notation
2. Constructor Notation

OBJECT
• Literal Notation

2
''

OBJECT
• Accessing an Object:
• You can access the properties and methods of an object using dot notation

OBJECT
• Accessing an Object:
• You can also access properties using square brackets

3
''

OBJECT
• Creating objects using
literal notation:

OBJECT
• Constructor Notation

4
''

OBJECT
• Updating an Object:

OBJECT

• Creating Many Objects:

• Sometimes you will want several objects to represent similar things.

• Object constructors can use a function as a template for creating objects.

• First, create the template with the object's properties and methods.

5
''

OBJECT

• Constructor Function

• The this keyword is used

instead of the object

name to indicate that the

property or method

belongs to the object that

this function creates.

OBJECT
• Constructor Function

• Each statement that creates a new property or method for this object ends
in a semicolon (not a comma, which is used in the literal syntax).
• The name of a constructor function usually begins with a capital letter (unlike
other functions, which tend to begin with a lowercase character).
• The uppercase letter is supposed to help remind developers to use the new
keyword when they create an object using that function.

6
''

OBJECT
• Creating instances of the object using the constructor function.
• The new keyword followed by a call to the function creates new object.
• The properties of each object are given as arguments to the function.

OBJECT

• Creating objects using


constructor syntax

7
''

OBJECT
• Create & access objects
constructor notation

OBJECT
• Adding and removing properties

8
''

• Recap: Ways to create objects

OBJECT

9
''

OBJECT
• Arrays are objects:
• Arrays are a special type of objects

OBJECT

• Arrays of Objects & Objects in Arrays:

• You can combine arrays and objects to create complex data structures.

• Arrays can store a series of objects (and remember their order)

• Objects can hold arrays (as values of their properties)

10
''

OBJECT

OBJECT

11
''

OBJECT
• What are built-in objects?
• Browsers come with a set of built-in objects that act like a toolkit for creating
interactive web pages.
• The objects you create will usually be specifically written to suit your needs.
• Built-in objects contain functionality commonly needed by many scripts.
• Built-in objects help you get a wide range of information such as the width of the
browser window, or the length of text a user entered into a form field.
• You access their properties or methods using dot notation, just like you would access
the properties or methods of an object you had written yourself.

OBJECT
• Three groups of Built-in Objects:
• Browser Object Model:
• Contains objects that represent the current browser window or tab. It
contains objects that model things like browser history and the device's
screen.
• Document Object Model:
• Uses objects to create a representation of the current page. It creates a new
object for each element (and each individual section of text) within the
page.
• Global JavaScript Objects:
• Represent things that the JavaScript language needs to create a model of.
For example, there is an object that deals only with dates and times.

12
''

OBJECT
• Browser Object Model:

OBJECT
• Document Object Model:

13
''

OBJECT
• Global JavaScript Objects:

OBJECT

• Dear Students:

• You are required reading the part


of built-in objects, page number 120
until the end of chapter Three.

• You will find most of built-in objects


with examples.

14
''

15
"CIT-UoB" ""

JAVASCRIPT
Haider M. Habeeb

JAVASCRIPT

Document Object Model


DOM
Part I

1
"CIT-UoB" ""

ATTENTION
• You are required to read chapter four of the
reference.

DOM

• The Document Object Model (DOM) specifies:


• how browsers should create a model of an HTML page.

• how JavaScript can access and update the contents of a web page while it is in
the browser window.

• The DOM is neither part of HTML, nor part of JavaScript;

• DOM is a separate set of rules.

2
"CIT-UoB" ""

DOM

• The DOM tree is a model of a web page

• When a browser loads a web page:


• it creates a model of that page,

• The model is called a DOM tree,

• and it is stored in the browsers' memory,

• DOM tree consists of four main types of nodes.

DOM
• Types of Nodes:
1. The Document Node
• Represents the entire page

2. Element Nodes
• Describe the structure of an HTML page.
3. Attribute Nodes
• Part of the element

4. Text Nodes
• It can be reached during the element

3
"CIT-UoB" ""

DOM TREE
• Body Of HTML
Page

DOM TREE

4
"CIT-UoB" ""

WORKING WITH THE DOM TREE

• Accessing and updating the DOM tree involves two steps:

1. Locate the node that represents the element you want to work with.

2. Use its text content, child elements, and attributes.

WORKING WITH THE DOM TREE

• STEP 1: ACCESS THE ELEMENTS

• DOM Queries
1. Select an Individual Element Node

2. Select Multiple Elements (Nodelists)

• Traversing the DOM.


3. Traversing Between Element Nodes

5
"CIT-UoB" ""

DOM TREE
• SELECT AN INDIVIDUAL ELEMENT NODE
1. getElementByld()
• Uses the value of an element's id
attribute
2. querySe1ector()
• Uses a CSS selector, and returns the first
matching element.
3. Traversing from one element to
another within the DOM tree

DOM TREE
• SELECT MULTIPLE ELEMENTS (NODELISTS)
1. getElementsByClassName()
• Selects all elements that have a specific
value for their class attribute.
2. getElementsByTagName()
• Selects all elements that have the specified
tag name.
3. querySelectorAll()
• Uses a CSS selector to select all matching
elements.

6
"CIT-UoB" ""

DOM TREE
• TRAVERSING BETWEEN ELEMENT NODES
• parentNode
• Selects the parent of the current
element node.
• previousSibling / nextSibling
• Selects the previous or next sibling from
the DOM tree.
• firstChild / lastChild
• Select the first or last child of the current
element.

DOM TREE
• STEP 2: WORK WITH THOSE ELEMENTS
• Access / Update Text Nodes
• nodeValue
• This property lets you access or update
contents of a text node.
• To access the text node on the right:
• 1. Select the <l i >element
• 2. Use the firstChild property to get the text
node
• 3. Use the text node's only property
(nodeValue) to get the text from the
element

7
"CIT-UoB" ""

DOM TREE
• STEP 2: WORK WITH THOSE ELEMENTS
• Work With HTML Content
• innerHTML
• textContent

DOM TREE
• STEP 2: WORK WITH THOSE ELEMENTS
• Access Or Update Attribute Values
• className /id
• Lets you get or update the value of the cl ass
and id attributes.
• hasAttribute()
• checks if an attribute exists.
• getAttribute()
• gets attribute’s value.
• setAttribute()
• updates the value.
• removeAttribute()
• removes an attribute.

8
"CIT-UoB" ""

DOM TREE

• Methods that return a single element node:


• getElementByld(‘id’)

• querySelector(‘css selector’)

DOM TREE

• Methods that return one or more elements (as a nodelist):


• getElementsByClassName(‘class’)

• getElementsByTagName(‘tagName’)

• querySelectorAll(‘css selector’)

9
"CIT-UoB" ""

DOM TREE
• Selecting elements using id attributes

DOM TREE
• NodeLists: DOM queries that return more than one element

• When a DOM method can return more than one element, it returns a Nodelist (even
if it only finds one matching element).

• Nodelists look like arrays and are numbered like arrays, but they are not actually
arrays; they are a type of object called a collection.

• Nodelist has properties and methods, notably:


• length property
• item() method

10
"CIT-UoB" ""

DOM TREE

DOM TREE

11
"CIT-UoB" ""

DOM TREE

DOM TREE

12
"CIT-UoB" ""

DOM TREE

• Selecting An Element From A NodeList

• There are two ways to select an element from a Nodelist:


• The item() method.

• Array syntax.

• Both require the index number of the element you want.

DOM TREE
• The Item() Method:

13
"CIT-UoB" ""

DOM TREE
• Array Syntax

DOM TREE
• SELECTING ELEMENTS USING CLASS ATTRIBUTES

14
"CIT-UoB" ""

DOM TREE
• SELECTING ELEMENTS BY TAG NAME

DOM TREE
• SELECTING ELEMENTS USING CSS SELECTORS

15
"CIT-UoB" ""

DOM TREE
• LOOPING THROUGH A NODELIST

16

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy