Intro to JavaScript & DOM
JavaScript Outline
•
•
•
•
•
•
Introduction
Variables & data types
Control statements
Arrays
Functions
Objects
JavaScript Quick facts
• Netscape was battling with IE and wanted a
lightweight component to compete with
Microsoft VB.
• Created by Brendan Eich (creator of Mozilla
Foundation) in 1995 while at Netscape.
CSE 3345
3
JavaScript Quick facts
• JavaScript was described by Brendan as,
“something that had to ‘look like Java’ only
less so and be Java’s dumb kid brother or boyhostage sidekick.”
• Had to be created in 10 days, or something
worse would have been developed.
CSE 3345
4
JavaScript Disclaimer
• A lot of people hate JavaScript!
• A lot of the people that hate JavaScript really
just don’t understand it.
• There are good parts and bad parts.
CSE 3345
5
3 Ways Use JS
• Inline
• Embedded
• External
CSE 3345
6
Inline Example
<div onclick="alert('this is a horrible idea');">
Click me
</div>
CSE 3345
7
Embedded Example
<html>
<head>
<script type="text/javascript">
window.onload = function() { alert('window loaded'); };
</script>
</head>
</html>
CSE 3345
8
External Example
index.html
<html>
<head>
<!-- Make sure you always use an opening and closing <script> tag;
else your script might not load -->
<script type="text/javascript" src="test.js"></script>
</head>
</html>
test.js
window.onload = function() { alert('window loaded'); };
CSE 3345
9
Same as CSS
• Reasons to use each method are the same as
CSS.
• External is preferred!
CSE 3345
10
JS characteristics
• It is a dynamic and weakly typed language.
• Dynamic type means that there are no
compile time checks to deduce variable type
and type conversions.
• Weakly typed mean the language will figure
out for itself how to convert variables of
different type.
CSE 3345
11
Strongly Typed Example
Test.java:
public class Test {
public static void main(String args[]) {
String x = "2";
int num = 7;
num += x;// Integer.parseInt(x);
System.out.println(num);
}
}
Test.java:6: error: inconvertible types
num += x;// Integer.parseInt(x);
^
required: int
found:
String
1 error
CSE 3345
12
Weakly Typed Example
var x = "2";
var num = 7;
num += x;
console.log(num); //72
CSE 3345
13
Outputting text to the console
• The web console provides a heads up display
for the web by letting users see error
messages and other logged information.
• console.log() – Outputs a message to the web
console. Extremely useful for debugging!
Outputting text to the console
Print strings
console.log(“Hello “ + “world!”);
Print objects
var foo = ‘hello’;
var bar = 0x01;
console.log(foo + “ “ + bar + “!”);
JavaScript Outline
•
•
•
•
•
•
Introduction
Variables & data types
Control Statements
Arrays
Functions
Objects
Declaring variables
• Variables are declared using the var keyword.
• JavaScript does not allow variables to be
declared with a specific type (int, float,
boolean, etc).
• JavaScript does have different data types
JavaScript types
typeof
typeof
typeof
typeof
typeof
typeof
typeof
typeof
4; // number
0xFF; // number
x; // undefined
true; // boolean
"String"; // string
{}; // object
[] ; // object
function() { alert("hi!"); }; // function
To var, or not to var?
• Any variable declared without the var
keyword becomes a global variable.
• That means un-varred variables in methods
automatically are global.
CSE 3345
19
Truthy and falsy values
Any value can be converted to a boolean
according to the following rules:
1. false, 0, the empty string (“”), NaN, null, and
undefined all become false.
2. All other values become true.
CSE 3345
20
Truth and Falsy in Action
var c = (false == 0); // true
var d = (false == ""); // true
var e = (0 == ""); // true
//null and undefined are only equal to themselves
and each other
var f = (null == false); // false
var g = (null == null); // true
var h = (undefined == undefined); // true
var i = (undefined == null); // true
//NaN is not equivalent to anything
var j = (NaN == null); // false
var k = (NaN == NaN); // false
CSE 3345
21
Comparing for equality
• The Equals operator is ==. Compares “truthy”
and “falsy” values of variables.
• Strict equals operator is ===. Always returns
false when the operands are of different
types.
CSE 3345
22
Always use ===
• To avoid unintended results, always use the
strict equals operator.
CSE 3345
23
String operators
• Use the + operator to concatenate two strings
together.
var x = “hello” + “ world”;
• Use the += operators to append two existing
strings.
var x = “hello”;
x += “ world”;
CSE 3345
24
Converting strings to numbers
• parseInt() – parses a string object and returns an
integer of the specified radix or base. You should always
specify a base.
– parseInt(“010”, 2);
– parseInt(“010”, 10);
// 2
// 10
• parseFloat() – parses a string object and returns a
floating point number. Always uses base 10.
– parseFloat(“10.44”);
CSE 3345
//10.44
25
Converting strings to numbers
• You can also prepend a string with a + to
convert the string to a number.
var string = "50";
console.log(string + 100); // 50100
console.log(+string + 100); // 150
CSE 3345
26
JavaScript Outline
•
•
•
•
•
•
Introduction
Variables & data types
Control Statements
Arrays
Functions
Objects
Control Statements
• JavaScript supports the typical list of control
statements.
1.
2.
3.
4.
5.
6.
7.
if, else, else if
while
do while
for
switch
break
continue
CSE 3345
28
Control Statements
• In addition to that list, js has a “for in”
statement.
• Use it to iterate over properties of an object.
• Be careful using “for in” for arrays. Sometimes
an object will have properties that you’re
unaware of and give weird output.
CSE 3345
29
For in example
// Initialize object.
a = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"} ;
// Iterate over the properties.
var s = "“;
for (var key in a) {
s += key + ": " + a[key];
s += "<br />";
}
document.write (s); // Output:
// a: Athens
// b: Belgrade
// c: Cairo
CSE 3345
30
Bad Part of JavaScript
• Always place an opening brace “{“ on the
same line as the control statement or
function.
• Undesired results can occur if you don’t follow
this practice.
• See here for details
CSE 3345
31
JavaScript Outline
•
•
•
•
•
•
Introduction
Variables & data types
Control Statements
Arrays
Functions
Objects
Arrays
• Arrays are a special type of object that have a length
property.
• Accessing a value that is outside of the array bounds
returns undefined.
• The length property returns the length of the array.
• The length is also one more than the highest index.
• The length of an array isn’t always the number of items in
the array.
CSE 3345
33
Array Length Bad Part
var x = ["dog", "cat", "monkey"];
x.length; //3
x[100] = "aligator";
x.length; //101
CSE 3345
34
Bad Array Initialization
>
>
>
>
>
3
var a = new Array();
a[0] = "dog";
a[1] = "cat";
a[2] = "hen";
a.length
> var a = new Array(); //bad
CSE 3345
35
Good Array Initialization
> var a = ["dog", "cat", "hen"];
> a.length
3
> var a = []; //good
CSE 3345
36
Array Methods
Method name
Description
a.toString()
a.toLocaleString()
a.concat(item[, itemN])
Returns a new array with the items added on to it.
a.join(sep)
a.pop()
Removes and returns the last item.
a.push(item[, itemN])
Push adds one or more items to the end.
a.reverse()
a.shift()
a.slice(start, end)
Returns a sub-array.
a.sort([cmpfn])
Takes an optional comparison function.
a.splice(start, delcount[, itemN])
Lets you modify an array by deleting a section and
replacing it with more items.
a.unshift([item])
Prepends items to the start of the array.
CSE 3345
37
JavaScript Outline
•
•
•
•
•
•
Introduction
Variables & data types
Control Statements
Arrays
Functions
Objects
Functions
• Almost like typical C/C++ and Java functions,
except you don’t specify a return type.
function sayHello() {
alert(“hello world!”);
}
CSE 3345
39
Function with parameters
• Once again similar to C/C++ and Java, but you
don’t specify the data type of the parameters.
• You also don’t prefix the parameter name with
the var keyword.
function add(x, y) {
return x + y;
}
CSE 3345
40
The arguments object
• The arguments object is a local variable
available within all functions that contains an
entry for each argument passed to a function.
• The arguments object will also hold values for
parameters that are specified by the function.
CSE 3345
41
Arguments object example
function concat(parm1) {
var str = parm1;
for (var i = 0, len = arguments.length; i < len; i++) {
str += " " + arguments[i];
}
return str;
}
concat("1", "2", "3", "4"); //"1 1 2 3 4”
CSE 3345
42
Anonymous Function
• You can create functions that are not bounded
to an identifier.
alert((function(){return "hello";})());
CSE 3345
43
Functions are first class objects
• This means that JavaScript functions are just a
special type of object that can do all things
regular objects can do.
This allows
1. Functions to be stored as variables
2. Functions to be passed as a parameter to
another function.
3. You can return a function from another function.
CSE 3345
44
Functions stored as variables
function sayHi() {console.log(“hi”); }
var hi = sayHi;
hi(); // hi
• Note that when assigning a function to a variable,
you don’t place “()” after the function name.
• However, to execute the function with the
variable name, you must use “()”.
CSE 3345
45
Function as a parameter of another
function
function sayHi() { return "hi";}
function salutation(greeting, name) {
console.log(greeting() + " " + name);
}
var hi = sayHi;
salutation(hi, "Fred"); // hi Fred
CSE 3345
46
Function as a return value for another
function
function add(x,y) { return x + y; }
function subtract(x,y) { return x - y; }
function getOperation(x) {
var operation = x % 2 === 0 ? add : subtract;
return operation;
}
var operation = getOperation(2);
operation(5,3); // 8
CSE 3345
47
JavaScript Outline
•
•
•
•
•
•
Introduction
Variables & data types
Control Statements
Arrays
Functions
Objects
Objects
• Objects are a collection of name-value pairs
• The “name” part is a JavaScript string.
• The “value” part can be any JavaScript value.
CSE 3345
49
Creating Objects
var student = {
name: "Wade Wilson",
alias: "wwilson",
id: 12345678,
email: "[email protected]",
isPassing: true
};
CSE 3345
50
Object member variables are public
There are no access level modifiers (public, protected, private) to
prevent access to an object’s variables.
student.name; //"Wade Wilson"
student.alias; //"wwilson"
student.id; //12345678
student.email; //"[email protected]"
student.isPassing; //true
CSE 3345
51
Object member variables are public
Using the object literal syntax, we can access variables a second
way.
student["name"]; //"Wade Wilson"
student["alias"]; //"wwilson"
student["id"]; //12345678
student["email"]; //"[email protected]"
student["isPassing"]; //true
This approach makes it possible to calculate the member
variable at run-time with a dynamic string.
CSE 3345
52
Object Methods
var student = {
name: "Wade Wilson",
alias: "wwilson",
id: 12345678,
email: "[email protected]",
isPassing: true,
sayHi: function() {console.log("hi");}
};
student.sayHi(); //”hi”
CSE 3345
53
Your turn
Create a function to print each pattern
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*********
**********
CSE 3345
**********
*********
********
*******
******
*****
****
***
**
*
54
DOM
• Intro to JavaScript
• DOM
– About
– Tree / nodes
– Accessing elements
– Creating elements
– Deleting element
Quick facts
• DOM – document object model
• Is a cross-platform language agnostic convention for
representing HTML, XHTML, and XML documents.
• Think of the DOM as a family tree which represents a
document.
• The DOM represents the document as a structured
group of nodes/objects that have properties and
methods.
HTML to DOM Tree
<html>
<head><title>DOM Test</title></head>
<body>
<p class="text" style="color:red">I am some text.</p>
</body>
</html>
HTML
HEAD
BODY
class: text
TITLE
P
style
color: red
CSE 3345
58
HTML to DOM Tree
document
HTML
HEAD
BODY
class: text
TITLE
P
style
color: red
CSE 3345
59
Live DOM Viewer
• Visit the Live DOM Viewer to see the DOM in
action.
CSE 3345
60
DOM API
• API – application programming interface
• Provides capabilities to change a document’s
structure, style, and content.
• In the DOM, everything in the document
becomes nodes (elements, text, attributes,
comments, etc) and forms a node tree.
CSE 3345
61
Getting access to the DOM from JS
• Each webpage loaded in the browser has its
own document object.
• The document object serves as the entry point
to the web page’s content aka the DOM tree.
CSE 3345
62
How to access the DOM in js
//JavaScript code
//this returns an array of all the div elements in
//the HTML document.
var divs = document.getElementsByTagName("div");
CSE 3345
63
DOM API
• Allows developers to access nodes in the DOM
Tree.
• Each node is actually a JavaScript object.
• Therefore, each object can have properties
and methods
CSE 3345
64
A few DOM traversing methods
• getElementByID(id) – get the element with the specified
id or null if an element wasn’t found.
• getElementsByTagName(tag) – returns an array of all
elements with the specified tag.
• getElementsByClassName(class) – returns an array of
all elements which have the given class name.
CSE 3345
65
Node Properties
document
HTML
HEAD
BODY
class: text
TITLE
P
style
color: red
CSE 3345
66
A few node Properties
•
•
•
•
•
•
•
•
innerHTML – the textual value of the node
nodeName – the name of the node
nodeValue – the value of the node
parentNode - the parent node of the node
childNodes – the child nodes of the node
attributes – the attributes of the node
firstChild – the first child of the node
nextSibling- the next sibling of the node
CSE 3345
67
nodeValue
• nodeValue can return different things
depending on what the node is
• Attribute – the value will be the value of the
attribute.
• Text – the value will be the text content
• Element – the value will be null
CSE 3345
68
Node Trees
• All nodes in the tree can be accessed and their
contents can be modified or deleted.
• New nodes can be created and inserted into
the tree.
CSE 3345
69
DOM manipulation methods
• removeChild(node) – remove a child node from the current
node.
• createElement(element) – create an element node of the
specified type.
• appendChild(node) – insert a child node to the current node.
• setAttribute(name, value) – set a new attribute
with the specified name and value to this node.
CSE 3345
70
Using the DOM API
• We can navigate to any section of the DOM tree
by using properties.
–
–
–
–
firstChild
lastChild
nextSibling
previousSibling
• Once we’ve found the node we want, we can set
almost any HTML attribute or data attribute and
CSS property.
CSE 3345
71
Using DOM to change HTML
• Use the properties of each node to change
specific things
– innerHTML
– setAttribute()
CSE 3345
72
Using DOM to change CSS
• Each element node has a style property.
• Using style, you change specific CSS properties
for the element’s inline style.
• Note this will not fetch CSS from embedded or
external declarations.
CSE 3345
73
DOM CSS Example
//changes the body element's inline color style to be red
document.body.style.color = "red";
CSE 3345
74
DOM References
• Sitepoint
• Use the intellisense feature of Chrome Web
Inspector to find available methods and
properties.
CSE 3345
75
DOM Example
http://cssdeck.com/labs/collab/knejnp4j/0
http://jsfiddle.net/blinkmacalahan/vfVM6/6/
CSE 3345
76
© Copyright 2026 Paperzz