0% found this document useful (0 votes)
2 views16 pages

Week 9 Lecture 1

The document covers JavaScript DOM manipulation techniques, including methods like getElementById and createElement, along with examples of manipulating HTML elements and handling input values. It also discusses Number and Math objects in JavaScript, explaining their properties and methods for number manipulation. Additionally, it provides examples of converting data types and creating dynamic HTML elements such as lists and tables using JSON data.

Uploaded by

danthebard
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Week 9 Lecture 1

The document covers JavaScript DOM manipulation techniques, including methods like getElementById and createElement, along with examples of manipulating HTML elements and handling input values. It also discusses Number and Math objects in JavaScript, explaining their properties and methods for number manipulation. Additionally, it provides examples of converting data types and creating dynamic HTML elements such as lists and tables using JSON data.

Uploaded by

danthebard
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

CSC365 Week 9 Lecture 1

JavaScript
Dom Manipulation.......................................................................................................................................3
Example 1 – getElementById().................................................................................................................3
Example 2 – getElementsByTagName()...................................................................................................3
Example 3 - createElement(), createTextNode(), appendChild().............................................................4
Example 4 - setAttribute()........................................................................................................................4
Example 5 - typeof() on field with a number part 1.................................................................................5
Example 6 - typeof() on field with a number part 2.................................................................................5
Example 7 - removeChild()......................................................................................................................5
DOM Manipulation - Unordered List Example.....................................................................................6
DOM Manipulation - Table Example....................................................................................................7
Number and Math Objects..........................................................................................................................9
Number Object........................................................................................................................................9
Number Object Example 1...................................................................................................................9
Number Object Example 2.................................................................................................................10
Properties – Example 3......................................................................................................................10
Converting Strings to Number – Example 4.......................................................................................10
Math Object...........................................................................................................................................11
Helpful Number Methods..................................................................................................................11
Math Example 1.................................................................................................................................11
Spread Syntax........................................................................................................................................11
Math Example 2.................................................................................................................................11
Math Example 3.................................................................................................................................11
Math Example 4.................................................................................................................................12
Simple Math..............................................................................................................................................12
Math Operations – Example 1...............................................................................................................12
Precedence – Example 2........................................................................................................................12
Fake Numbers – Example 3...................................................................................................................13
Shorthand notation – Example 4...........................................................................................................13
Converting Strings, Numbers, and Booleans.............................................................................................14
Strings to Numbers................................................................................................................................14
Example 1..........................................................................................................................................14
Example 2..........................................................................................................................................14
Numbers to Strings................................................................................................................................14
Example 3..........................................................................................................................................14
Converting from Booleans.....................................................................................................................14
Example 4..........................................................................................................................................14
Converting to Booleans.........................................................................................................................15
Example 5..........................................................................................................................................15
DOM Manipulation
Watch the video
 As developers, we sometimes need to manipulate the DOM on the fly.
 This means we need to access elements and change them in some way.
 The DOM, if you remember, is the Document Object Model.
 An element, if you remember, is the start tag, the end tag, and everything in between.
 We will learn how to create or access elements on the page and change them.
 How can we access elements on the page and what is returned?
JAVASCRIPT RETURNED NOTES
document.getElementById("table"); A single element whose "id" is table. Remember that an id is unique on
<table id="table"> the page. That is why only one
</table> value is returned.
document.getElementsByClassName("ancho All elements with class="anchor" A NodeList is returned. Since more
r"); <a href="#" class="anchor">link 1</a> than one element can have the
<a href="#" class="anchor">link 2</a> class "anchor", a list is
returned.
document.getElementsByTagName("div") All elements with tag name = "div" We can get whatever tags we want.
<div>div 1</div> Since a tag is not unique, a list
<div>div 2</div> of elements is returned.
document.querySelector("a.anchor"); The FIRST anchor tags with Notice we can use a CSS selector
class="anchor" in our querySelector. Only the
<a href="#" class="anchor">link 1</a> FIRST element that matches is
<a href="#" class="anchor">link 2</a> returned!
document.querySelectorAll("a.anchor"); All anchor tags with class="anchor" We can still use a CSS selector in
<a href="#" class="anchor">link 1</a> our querySelectorAll. EVERY
<a href="#" class="anchor">link 2</a> element that matched the query is
returned in a list.

Example 1 – getElementById()
Watch the video
We can set the innerHTML value for an element with element.innerHTML = “HTML or Text”
<div class="col-sm-5"> // Access the element you want to manipulate
<label>Output</label> var myOutput = document.getElementById("output");
<div id="output"></div> myOutput.innerHTML += "DOM Manipulation Rox!<br/>";
</div> myOutput.innerHTML += "<strong>yay!</strong><br/>";

Example 2 – getElementsByTagName()
Watch the video
<h3 id="heading"> // Again, grab the element you want to
Example 2 of 7 manipulate
var heading =
</h3>
document.getElementsByTagName("h3");
// returns node list
heading[0].innerHTML = "I have achieved DOM
control!";

 We can manipulate the information on the page with element.innerHTML using vanilla JS
 This gets the job done but is not the best practice
 A proper way to modify the document is to properly update the DOM (see MDN for more)
 This is where understanding the DOM hierarchy comes to play
Example 3 - createElement(), createTextNode(), appendChild()
Watch the video
// We are updating the DOM properly in this example since
// we are creating elements and not using the property innerHTML.
// Inspect the page with Chrome tools and find id="heading"
// Create a paragraph tag with text and add it to the document.
var paragraph = document.createElement('p');
paragraph.appendChild(document.createTextNode('I have achieved DOM control '));

// Add the strong tag and text, then append it


// to the paragraph
var strong = document.createElement('strong');
strong.appendChild(document.createTextNode('properly!'));
paragraph.appendChild(strong);

// Get access to the heading and then add the


// paragraph as a sibling
var heading = document.getElementById("heading");
heading.parentNode.appendChild(paragraph);

/*
* Notice the hierarchy:
> html
> body
> heading
> paragraph
> textNode
> strong
*/

* Notice the hierarchy:


> html
> body
> heading
> paragraph
> textNode
> strong

Example 4 - setAttribute()
Watch the video
A common task we handle is getting and setting the values of input fields.
// Create an input tag with text and add it to the document
var input = document.createElement('input');

// Set some attributes and set the value


input.setAttribute("class", "border border-primary");
input.setAttribute("type", "number");
input.setAttribute("id", "myInput");
input.value = "123";

// Get access to the heading and then add the input as a sibling
var heading = document.getElementById("heading");
heading.parentNode.appendChild(input);

● Use .value to get or set the value of an input element


● When you get a value, it is a string even if a number is in the input field
Example 5 - typeof() on field with a number part 1
Watch the video
This example only works if you have created the element in the previous example. Enter a number in the
newly created input field and then execute the JavaScript below to see the type for the value.
// Access the value from our input field using .value
var input = document.getElementById('myInput');
var myInputValue = input.value;

print(`myInputValue: ${myInputValue}`);
print(`typeof myInputValue: ${typeof myInputValue}`);

Example 6 - typeof() on field with a number part 2


Watch the video
Create a number input type and see what its value type is.
// "value" is a string whether you
// build <input type="text" /> or when you
// build <input type="number" />
var inputNum = document.createElement('input');
inputNum.setAttribute("type", "text");
inputNum.setAttribute("id", "myInputNum");
inputNum.value = 1;
heading.parentNode.appendChild(inputNum);

print("inputNum: " + document.getElementById("myInputNum").value);


print("inputNum: " + typeof document.getElementById("myInputNum").value);

Example 7 - removeChild()
Watch the video
Removing elements involves targeting the element to remove and then removing it via its parent.
// Removing elements
// get the elements to remove
var input1 = document.getElementById('myInput');
var input2 = document.getElementById('myInputNum');
// remove from the parent
input1.parentNode.removeChild(input1);
input2.parentNode.removeChild(input2);

// We'll grab the heading as reference to remove our paragraph tag


var heading = document.getElementById("heading");
heading.parentNode.removeChild(heading.parentNode.lastChild);
DOM Manipulation - Unordered List Example
Watch the video
Let’s build and execute a DOM manipulation script. We will build an unordered list on-the-fly and add it
to our page.
// Find the first instance of <div class="col-12 col-lg-5">
// in our HTML file
let ulHolder = document.querySelector("div.col-lg-5");

// Remove the inner html inside of this div


ulHolder.innerHTML = "";

// Create the unordered list and set its attributes


let ul = document.createElement("ul");
ul.setAttribute("class", "mt-5");
// or
ul.classList.add("mt-5");

// Define the list items


let items = ["coffee", "tea", "milk"];

// Loop through each of the items, build the list item


// element and add it to the unordered list element.
items.forEach((item)=>{
let li = document.createElement("li");
let textNode = document.createTextNode(item);
li.appendChild(textNode);
ul.appendChild(li);
});

// Add the ul to the ulHolder element


ulHolder.appendChild(ul);

 The "div.col-lg-5" represents an element that we already have on the page.


o <div class="col-12 col-lg-7>Left Side</div>
<div class="col-12 col-lg-5>Right Side</div>
 If you do not have this element on your page, then the script will not work properly for you. You
will want to add it to your page or target an element that is already on your page,
 Notice how easy it is to remove HTML from the page. We can simply target an element and set
its innerHTML attribute to the empty string and the HTML will vanish!
 We are using the JavaScript we learned previously to create elements and set attributes.
o I have introduced a new technique.
o We can add and remove classes to a class attribute
 ul.classList.add("someClass");
 ul.classList.remove("someClass");
o If you add a class that already exists, it is okay; only one will be added.
o If you remove a class that does not exist already, it is okay; no errors are thrown.
o This technique is popular with it comes to hiding and showing elements on a page
 Next, we build a list of items, loop through them, create the LI tag, add the item to the list item,
and then add the list item to the unordered list.
 Finally, we add the unordered list to the ul holder.
DOM Manipulation - Table Example
Watch the video
Let’s see what a real working example would look like. Let’s pretend that we have retrieved data from a
web application. We can store this data using something called JSON.

JSON stands for JavaScript Object Notation. When we create objects in JavaScript (with key/value pairs),
we are building JSON.

Note: JSON will always start with left bracket "[" or left curly brace "{."

When JSON starts with a left curly brace, then we know that the JSON represents one object. When
JSON starts with a left bracket, then we have an array of objects.

Let’s create an array of students with first name, last name, and major.
[
{"firstName" : "John", "lastName" : "Doe", "major" : "Mathematics"},
{"firstName" : "Jane", "lastName" : "Doe", "major" : "Computer Science"}
]

Notice that the JSON starts with a left bracket. This means we are working with an array of objects. In
this case, we are working with an array of students.
Let’s work on some JavaScript that will build the table of students. We will use DOM manipulation to
achieve this.
// Find the first instance of <div class="col-12 col-lg-5">
// in our HTML file
let tableHolder = document.querySelector("div.col-lg-5");

// Remove the inner html inside of this div


tableHolder.innerHTML = "";

// Create the table


let table = document.createElement("table");
table.setAttribute("class","table table-hover table-striped table-bordered mt-5");

// Create the header row


let headerRow = document.createElement("tr");

// Define the table headings


let headings = ["First Name", "Last Name", "Major"];

// Build the thead element


let thead = document.createElement("thead");

// Loop through each of the headings and add it to the headerRow


headings.forEach((heading)=>{
let th = document.createElement("th");
let textNode = document.createTextNode(heading);
th.appendChild(textNode);
headerRow.appendChild(th);
});

// Add the header row to the thead element


thead.appendChild(headerRow);

// Create the tbody element


let tbody = document.createElement("tbody");

// Build the JSON data (students)


let studentArray = [
{"firstName" : "John", "lastName" : "Doe", "major" : "Mathematics"},
{"firstName" : "Jane", "lastName" : "Doe", "major" : "Computer Science"},
{"firstName" : "Mark", "lastName" : "Doe", "major" : "Geography"}
];

// Loop through each student to add a student record


// to the table
studentArray.forEach((student)=> {
// Create the row for this student record
let row = document.createElement("tr");

for (field in student) {


// Create the table data (td) cell for each
// field in the student object
let td = document.createElement("td");
let textNode = document.createTextNode(student[field]);
td.appendChild(textNode);
row.appendChild(td);
}

tbody.appendChild(row);
});

// Add the thead and tbody elements to the table


table.appendChild(thead);
table.appendChild(tbody);

// Add the table to the tableHolder div


tableHolder.appendChild(table);
Number and Math Objects
Number Object
The Number JavaScript object is a wrapper object allowing you to work with numerical values.
Remember, when working with the Number object:
● If the argument cannot become a number, it returns NaN.
● In a non-constructor context (i.e., without the new operator), Number can be used to perform a
type conversion.

A Number object is created using the Number() constructor.


let five = new Number('5');

A primitive type object number is created using the Number() function.


let six = Number('6'); // no new

Number Object Example 1


Watch the video
// create a number object
var five = new Number('5');
// create a primitive number
var six = Number('6');
// create another primitive number
var seven = 7;

print("five===5: " + (five === 5));


print("five instanceof Number: " + (five instanceof Number));
print("typeof five: " + (typeof five));
print("");
print("six===6: " + (six=== 6));
print("six instanceof Number: " + (six instanceof Number));
print("typeof six: " + (typeof six));
print("");
print("seven===7: " + (seven === 7));
print("seven instanceof Number: " + (seven instanceof Number));
print("typeof seven: " + (typeof seven));

Using strict equality, a number object is not equal to a primitive value.


Helpful Number Methods:
Number.toExponential(myNum) Returns a string representing the number in exponential notation.
Number.toFixed(myNum) Returns a string representing the number in fixed-point notation.
Number.toPrecision(myNum) Returns a string representing the number to a specified precision in
fixed-point or exponential notation.
Number.toString(myNum) Returns a string representing the specified object in the specified
radix (base).
Number.valueOf(myNum) Returns the primitive value of the specified object.
Number Object Example 2
Watch the video
var five = Number('5');
var seven = 7;

// Number methods available to both the object and primitive


print("five.toExponential(2): " + (five.toExponential(2)));
print("seven.toExponential(2): " + (seven.toExponential(2)));
print("five.toFixed(2): " + (five.toFixed(2)));
print("seven.toFixed(2): " + (seven.toFixed(2)));
print("five.toPrecision(4): " + (five.toPrecision(4)));
print("seven.toPrecision(4): " + (seven.toPrecision(4)));
print("five.toString(): " + (five.toString()));
print("seven.toString(): " + (seven.toString()));
print("five.valueOf(): " + (five.valueOf()));
print("seven.valueOf(): " + (seven.valueOf()));

Properties – Example 3
Watch the video
// Some Interesting Number Properties
const bigInt = Number.MAX_SAFE_INTEGER; // the largest representable
integer
const max = Number.MAX_VALUE; // the largest representable number
const minInt = Number.MIN_SAFE_INTEGER; // the smallest representable
integer
const min = Number.MIN_VALUE; // the smallest representable
number
const nInf = Number.NEGATIVE_INFINITY; // the same as -Infinity
const nan = Number.NaN; // the same as NaN
const inf = Number.POSITIVE_INFINITY; // the same as Infinity

Converting Strings to Number – Example 4


Watch the video
There are many ways to convert a String to a Number.
var num = "5"; // String
print(`parseInt(num): ${parseInt(num)}`); // default way (no radix)
print(`typeof parseInt(num): ${typeof parseInt(num)}`);
print(`parseInt(num, 10): ${parseInt(num, 10)}`); // parseInt with radix
(decimal)
print(`parseFloat(num): ${parseFloat(num)}`); // floating point
print(`Number(num): ${Number(num)}`); // Number method
print(`typeof Number(num): ${typeof Number(num)}`);
print('');
print(`num / 1: ${num / 1}`); // diving by one
print(`num * 1 : ${num * 1 }`); // multiplying by one
print(`num - 0 : ${num - 0 }`); // minus 0
print(`+num : ${+num }`); // unary operator "+" (best way to convert a
number)
print(`typeof num ${typeof +num}`);
print(`typeof num/1 ${typeof (num/1)}`);
Math Object
Math is a built-in object that has properties and methods for mathematical constants and functions.
Helpful Number Methods
Math.abs(myNumber) Returns the absolute value of a number.
Math.ceil(myNumber) Returns the smallest integer greater than or equal to a number.
Math.floor(myNumber) Returns the largest integer less than or equal to a number.
Math.hypot(num1, num2) Returns the square root of the sum of squares of its arguments.
Math.max(myNumber) Returns the largest of zero or more numbers.
Math.min(myNumber) Returns the smallest of zero or more numbers.
Math.pow(myNumber) Returns base to the exponent power, that is, baseexponent.
Math.random(myNumber) Returns a pseudo-random number between 0 and 1.
Math.round(myNumber) Returns the value of a number rounded to the nearest integer.
Math.sqrt(myNumber) Returns the positive square root of a number.
Math.trunc(myNumber) Returns the integer part of the number x, removing any fractional digits.

Math Example 1
Watch the video
print(`Math.abs(-5): ${Math.abs(-5)}`);
print(`Math.ceil(1.3): ${Math.ceil(1.3)}`);
print(`Math.floor(1.3): ${Math.floor(1.3)}`);
print(`Math.random(): ${Math.random()}`);
print(`Math.trunc(1.3): ${Math.trunc(1.3)}`);

Note: there are static properties: E, LN2, LN10, LOG2E, PI, SQRT2 …
Spread Syntax
Spread syntax allows an iterable such as an array expression or string to expand in places where zero or
more arguments (for function calls) or elements (for array literals) are expected, or an object expression
to expand in places where zero or more key-value pairs (for object literals) are expected.
Math Example 2
Watch the video
// using .max() and .min() is limiting sometimes
// because of passing each number as a parameter.
print(`Math.max(1,2,3): ${Math.max(1,2,3)}`);
// using the spread syntax, we can pass an array to the functions
let numArray = [3, 2, 1, -5, 0];
print(`Math.max(...numArray): ${Math.max(...numArray)}`);
print(`Math.min(...numArray): ${Math.min(...numArray)}`);

Math Example 3
Watch the video
print(`Math.E: ${Math.E}`);
print(`Math.PI: ${Math.PI}`);
print(`Math.pi: ${Math.pi}`); //?
Math Example 4
Watch the video
print(`2**4: ${2**4}`); // Represents 2 to the 4th
print(`Math.pow(2,4) === 2 ** 4: ${Math.pow(2,4) === 2 ** 4}`);
print(`4**0.5: ${4**0.5}`);
print(`Math.pow(4,0.5) === 4 ** 0.5: ${Math.pow(4,0.5) === 4 ** 0.5}`);
print(`<br>Check out more Math methods <a target="_blank"
href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
Global_Objects/Math">MDN Math</a>`);

Simple Math
Math Operations – Example 1
Watch the video
print(`1+1: ${1+1}`);

print(`0.1 + 0.2: ${0.1 + 0.2}`);


// 0.30000000000000004 - the result of a floating-point calculation

// JavaScript numbers are really floating points. Due to inadequacies


// when representing numbers in base-2, as well as a finite machine,
// we are left with a format that is filled with rounding errors. We
// can use ".toFixed(x)" to assist, though;
print(`(0.1 + 0.2).toFixed(2): ${(0.1 + 0.2).toFixed(2)}`);

// toFixed(n) provides n length after the decimal point; toPrecision(x)


provides x total length.

print(`8 - 1: ${8 - 1}`);


print(`35/7: ${35/7}`);
print(`5/7: ${5/7}`);
print(``);
print(`-- modulo division --`);
print(`10 % 2: ${10 % 2}`);
print(`30 % 4: ${30 % 4}`);
print(`18.5 % 7: ${18.5 % 7}`);

Precedence – Example 2
Watch the video
// PEMDAS
// Please Excuse My Dear Aunt Sally
// P - parenthesis
// E - exponents
// M - multiplication
// D - division
// A - addition
// S - subtraction
var result = (1 + 3) * 2 / 2 + 1 - 4; // = 1
print(`result: ${result}`);
Fake Numbers – Example 3
Watch the video
// There are three special not-a-real-number values:
var result = Infinity; // result of e.g. 1/0
print(`result: ${result}`);

var result = -Infinity; // result of e.g. -1/0


print(`result: ${result}`);

var result = NaN; // result of e.g. 0/0, stands for 'Not a Number'
print(`result: ${result}`);

Shorthand notation – Example 4


Watch the video
// There's shorthand for performing math operations on variables:
var result = 5;
print(`result (result += 5): ${result += 5}`);
// "result += 5" is equivalent to "result = result + 5;." result is 10 now

print(`result (result *= 10): ${result *= 10}`);


// now result is 100

// Note: The plus and asterisk notation above can be replaced with
// division and subtraction notation.

// Postfix, Prefix, and Infix


// When using postfix notation, with the operator after operand (for
example, x++),
// the value, before incrementing, is returned.

// When using prefix notation, with the operator before operand (for
example, ++x),
// or infix notation with the operator between the operands (for example 1
+ 2)
// the value, after incrementing, is returned.

// Adding and Subtracting 1 using postfix notation


print(`result (result++): ${result++}`);
// After returning the value 100, the variable "result" is incremented
// by 1 and has a value of 101.
print(`result (result): ${result}`);

print(`result (result--): ${result--}`);


// After returning the value 101, the variable "result" is decremented
// by 1 and has a value of 100.
print(`result (result): ${result}`);

// Adding and Subtracting 1 using prefix notation


print(`result (++result): ${++result}`); // 101
print(`result (--result): ${--result}`); // 100
Converting Strings, Numbers, and Booleans
Some of the methods we use below we have already seen. However, we are looking at them from the
perspective of changing data types.
Strings to Numbers
Remember we can use the Number object to create numbers from strings.
Example 1
Watch the video
var numStr = "33.3";
var num = Number(numStr); // this creates a number value, *not* an instance of the Number object
print(`num: ${num}`);

We used some of these Number functions already, but this time we see numbers extracted from strings
that are more complicated.

Example 2
Watch the video
var volts = parseInt("16 volts", 10); // the " volts" is ignored, 16 is parsed in base 10
var speed = parseFloat("15.5 mph"); // the " mph" is ignored; parseFloat always assumes base
10
print(`volts: ${volts}`);
print(`speed: ${speed}`);

Numbers to Strings
Many data types in JavaScript have the .toString() method
Example 3
Watch the video
var five = 5;
var strFive = five.toString();
print(`strFive: ${strFive}`);
print(`typeof strFive: ${typeof strFive}`);

// We are simply using the prototypal function


// toString() to make the conversion.

Converting from Booleans


The example below shows a solution to convert a Boolean to a number and to a string.
Example 4
Watch the video
var bool = true;
var numBool = bool ? 1 : 0; // now we have a numeric value
var strBool = bool.toString(); // now we have string value
print(`numBool: ${numBool}`);
print(`strBool: ${strBool}`);
// another way to convert to a number
print(`bool*1 : ${bool*1}`);
print(`bool*1 : ${typeof (bool*1) }`);
Converting to Booleans
The examples below use the Boolean object construct which we covered already.
Example 5
Watch the video
print(`Boolean(1): ${ Boolean(1)}`);
print(`Boolean("make me true, please"): ${ Boolean("make me true, please")}`);
// remember, any non-empty string value is truthy…

You might also like