Write Javascript in HTML

Data Type

Working With Strings


Math & Number

Get User Input


Array

Function

Access HTML Element

Event Lisener


Messaging App
var message = document.getElementById("message");
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");button.addEventListener("click",function(){
var newMessage = document.createElement("li");//創建新的html element
newMessage.innerHTML = textbox.value; //取出textbox裡的東西
message.appendChild(newMessage);
});
If Statement
&& : and. || : or.

Switch Statement

Objects

var movie = {
title:"The Social Network",
releaseYear : "2010", //小心releaseYear 不要分開寫
duration:2.0,
actors:[
{
name:"Eisenberg",
hometown:"New York"
},
{
name:"Ronnie Mara",
hometown:"New York"
},
]
};document.write(movie.actors[0].name);
While Loop
The difference between Do-While Loop and While Loop is that the former will execute the code first and then check the condition. </br> mean change line.


For loop
We need to put the three things in the for loop. First one is variable. Second one is condition. Third one is the thing you want computer to execute after the loop finish.

Local Storage in Javascript
We can store user information even if user shot down their website. “name” in the fifth line means we store textbox value into the variable “name”.
var textbox = document.getElementById("textbox");
var button = document.getElementById("btn");button.addEventListener("click",function(){
localStorage.name = textbox.value;
})document.write(localStorage.name)

Variable in Javascript (3 ways)
Before 2015, using the var
keyword was the only way to declare a JavaScript variable. In 2015 version of ES6, which allows the use of the const
keyword to define a variable that cannot be reassigned, and the let
keyword to define a variable with restricted scope.
Distinguish
let : maybe re-assigned
const : can’t be re-assigned
ES6 Template Strings ` `
Template Strings use back-ticks (``
) rather than the single or double quotes we're used to with regular strings. Template Strings can contain placeholders for string substitution using the ${ }
syntax.
var name = "Brendan";
console.log(`Yo, ${name}`);
// => "Yo, Brendan"
ES6 Arrow function
const add = (a,b)=>{
consolo.log(a+b)}
we can use it in map function.
const a = [1,2,3]
a.map( n => console.log(n))
ES6 Object Literal
If the property name is equal to the variable name in an object, we can just write one time.
let person ={
firstName : firstName,
lastName : lastName
}//equal tolet person ={
firstName,
lastName
}
ES6 Array De-structure & Object De-structure
array de-structure
const a = [1,2,3]
const [first, ,third]=a
console.log( first, third)//1,3
object de-structure
const a = {
name:Sam,
age:25}
const { name, age } = a;
console.log(name, age)//Sam 25
Spread Operator
…
means all.
const a = [1,2,3,4,5]console.log(...a)//1 2 3 4 5
Async & Await
We can use setTimeOut to explain async concept.
console.log('Start')
setTimeout(()=>{console.log('wait!!')},3000)
console.log('End')
The result of the code :

We can see that when we wait 3sec for setTimeOut, console.log(‘End’) also running. That means we run setTimeout and console.log(‘End’) in the same time!! This is the concept of async.
onChange
Every time that there is something change, react will re-render and store the value in to input
DOM
The Document Object Model (DOM) is an application programming interface (API) for manipulating HTML and XML documents. The DOM also represents a document as a tree of nodes. It provides API that allows you to add, remove, and modify parts of the document effectively.
Node and Element
A node is a generic name of any object in the DOM tree. It can be any built-in DOM element such as the document. Or it can be any HTML tag specified in the HTML document like <div>
or <p>
.
An element is a node with a specific node type Node.ELEMENT_NODE
, which is equal to 1. For example: <p> and <div> are element. Following picture is about node value.

Node Relationships
Any single node has relationships to other nodes in the DOM tree. For example, <body>
is a child-node of the <html>
node, and <html>
is the parent of the <body>
node.
querySelector() & querySelectorAll()
The querySelector()
allows you to find the first element that matches one or more CSS selectors.
#Type selector : The following example finds the first h1
element and all h2
elements in the document
let firstHeading = document.querySelector('h1');let heading2 = document.querySelectorAll('h2');
#Class selector : The following example finds the first element with the menu-item
class
let note = document.querySelector('.menu-item');
#ID Selector : The following example finds the first element with the id #logo
let logo = document.querySelector('#logo');
link : https://www.javascripttutorial.net/javascript-dom/javascript-queryselector/
createElement
We can use document.createElement()
to create a new HTML element and attach it to the DOM tree.
let element = document.createElement(htmlTag);
Ex1 : Create a new div with id&class name and put sth into it.
let div = document.createElement('div');div.id = 'content';
div.className = 'note';div.innerHTML = '<p>CreateElement example</p>';
Ex2 :
let div = document.createElement('div');
let h2 = document.createElement('h2');h2.textContent = 'Add h2 element to the div';div.appendChild(h2);
Summary
- The
document.createElement()
creates a new HTML element. - The
element.appendChild()
appends an HTML element to an existing element.
createElement vs innerHTML
Using the innerHTML
causes the web browsers to re-parse(重解析) and recreate all DOM nodes inside the div element. Therefore, it is less efficient than creating a new element and appending to the div.
createElement : more secure, more efficient.
innerHTML : clean code
⚠️ You should use innerHTML only when the data comes from a trusted source like a database, otherwise, malicious(惡意) code may be injected and executed.
Method (new elements to the div)
createElement
let div = document.querySelector('.container'); let p = document.createElement('p');
p.textContent = 'JS DOM'; div.appendChild(p);
innerHTML
let div = document.querySelector('.container'); div.innerHTML += '<p>JS DOM</p>';
link : https://www.javascripttutorial.net/javascript-dom/javascript-innerhtml-vs-createelement/
appendChild()
The appendChild()
is a method of the Node
interface. We can add child node to the given parent node.
parentNode.appendChild(childNode);
insertBefore()
insertBefore()
function inserts a new node before a specified node.
For example : we want to insert a new node as the first list item.
let menu = document.getElementById('menu');let li = document.createElement('li'); li.textContent = 'Home'; menu.insertBefore(li, menu.firstElementChild);//output(in the list)
Home
About
Contact
insertAdjacentHTML()

Output :
