Week 9 Lecture 1
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 '));
/*
* 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');
// Get access to the heading and then add the input as a sibling
var heading = document.getElementById("heading");
heading.parentNode.appendChild(input);
print(`myInputValue: ${myInputValue}`);
print(`typeof myInputValue: ${typeof myInputValue}`);
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);
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");
tbody.appendChild(row);
});
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
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}`);
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 = NaN; // result of e.g. 0/0, stands for 'Not a Number'
print(`result: ${result}`);
// Note: The plus and asterisk notation above can be replaced with
// division and subtraction notation.
// 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.
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}`);