Javascript DOM Javascript is the most used programming

  • Slides: 82
Download presentation
Javascript & DOM

Javascript & DOM

Javascript is the most used programming language in 2019 according to Github and Stackoverflow

Javascript is the most used programming language in 2019 according to Github and Stackoverflow and maintains top positions on other top charts.

Javascript – main properties n n n n is a lightweight scripting language (language

Javascript – main properties n n n n is a lightweight scripting language (language used to control the browser) that is run on the client-side (browser) developed by Netscape and Sun Microsystems and introduced first in the Netscape Navigator 2. 0 is intended to add interactivity and dynamic functionality to HTML pages is interpreted, not compiled, inserted directly in HTML pages is an object-oriented language that inherits many features from Java, but it is not Java is understood by most browsers is an event-based language, weakly typed current standard version is ECMAScript 2019 (ES 10), but browser conformance is ECMAScript 2015 (ES 6) -2016 (ES 7)

What can Javascript do ? n n n it can detect the type of

What can Javascript do ? n n n it can detect the type of browser it can react to various events of the browser it can alter the structure of the html document (modify, delete, add tags on the run-time) it can validate data before being sent to the server it can not modify local (client) files

Base elements of Javascript n n Js inherits from Java simple data types, operators,

Base elements of Javascript n n Js inherits from Java simple data types, operators, instruction syntax Js has predefined objects: DOM-related and general objects: Array, Boolean, Date, Error, Eval. Error, Function, Math, Number, Object, Range Error, Reference. Error, Reg. Exp, String, Syntax. Error, Type. Error, URIError n n n Js has some global functions (not related to objects): decode. URI, decode. URIComponent, encode. URIComponent, eval, is. Finite, is. Na. N, parse. Float, parse. Int comments: // or /*…*/ Js is weakly-typed: a variable can be bound to a specific type, then to a different type, during the course of a program execution

Types and literals (constant values) n n n n numbers: integer (in base 2,

Types and literals (constant values) n n n n numbers: integer (in base 2, 8, 10, 16) and real boolean: true and false null undefined: a variable that does not have an assigned value; Na. N: not a number String (unicode chars): ‘text’, “something”, `text 1` etc. ; methods of the string class can be applied on any string literal (e. g. “sir”. length); `` can span over multiple lines vectors: [‘a’, , , ‘bbb’, ‘ccc’] will have 5 elements objects: lists of zero or more pairs “property : value” ex. : dog = {name: dog, type: animal, characteristics: get. Props(“dog”), age: 4}

null and undefined null – a value representing the absence of a value (like

null and undefined null – a value representing the absence of a value (like null in Java and C++ n undefined – a value of a variable that hasn’t got a value yet n Ex. : var x = null; // null var y; // undefined n

Variables n loosly-typed language: n n a variable can be bound to different types

Variables n loosly-typed language: n n a variable can be bound to different types during its lifetime; the value of a variable is automatically converted to other types when necessary the type of a variable needs not be declared a variable is declared with “var” or “let” or just by assigning a value to it: var name; root=“some text”; i = root+1; // i=“some text 1” let x = 2; n “let” variables have block scope and “var” or “no var” (i. e. variables declared without “var”, just by assigning a value to it) variables have global scope (if declared outside a function) or function scope (if declared inside a function)

Variables (cont. ) n n n a variable without a value assigned to it

Variables (cont. ) n n n a variable without a value assigned to it will be evaluated to “undefined” or Na. N (depending on the context) if it was declared with “var” or will give a run -time error if it was not declared with “var” a variable is global (decl. outside any function) or local to a function or has block scope (if declared with let ) function variables: var f = function(a, b) { return a+b; } f(2, 3) ; // calling the function

Constants n n n declare entities that don’t change value the scope of a

Constants n n n declare entities that don’t change value the scope of a constant is block-level Ex: const z = 10; const s = “web”; s = “programming”; // throws error !

Operators n n n n 3 types of expressions in Js: arithmetic (eval. to

Operators n n n n 3 types of expressions in Js: arithmetic (eval. to a number), string and boolean (eval. to true or false) assign operators: =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |= comparison operators: ==, !=, >, >=, <, <= arithmetic operators: %, /, ++, --, +, -, ** (power) bitwise operators: &, |, ^, ~, >>, <<, >>> logic operators: &&, ||, ! string operator: + (concatenation) special operators

Special operators n n n n n identity operators: === (eguality and of the

Special operators n n n n n identity operators: === (eguality and of the same type), !== (not equal and/or of different types) ternary operator: condition ? true-expr : false-expr comma: expr 1, expr 2, …, expr. N new: creates a new object this: refers to the calling object in a method typeof: typeof(“test”) => string delete: deletes an object or a property from an object or an element from a vector in: prop. Nameor. Number in object. Name instanceof: object. Name instanceof object. Type void: evaluates an expression without returning a value

Automatic type conversion system (implicit type coercion) when applying operators, javascript automatically convert parameters

Automatic type conversion system (implicit type coercion) when applying operators, javascript automatically convert parameters to the same type, depending on the context: a = “string”+2; => “string 2” b = 2+” 3” => “ 23” c =2+true => 3 d = “string”+false => “stringfalse” []==0 => true 10 -” 1” => 9 n

Instructions (borrowed from Java) conditional: if, switch “falsy values”: false, undefined, null, 0, Na.

Instructions (borrowed from Java) conditional: if, switch “falsy values”: false, undefined, null, 0, Na. N, “” n loop: for, do while, label, break [label], continue [label] n for (variable in object) { … statements …} : cycles through the properties of an object n for (variable of object) { … statements …} : “for. . . in” cycles over property names, “for. . . of” iterates over property values: n with (object) { … statements … } : sets the default object for a set of statements n exception handling instructions: try { … statements … } catch (exception) { … } throw expression; n

For cycles over arrays var a = [ 'x', 'y', 23 ]; a. Test

For cycles over arrays var a = [ 'x', 'y', 23 ]; a. Test = “foo”; for (i=0; i<a. length; i++) { console. log(a[i]); } // will print: x, y, 23 for (var i in a) { console. log(i); } // will print: 0, 1, 2, test for (var i of a) { console. log(i); } // will print: x, y, 23 a. for. Each(function(elem) { console. log(elem); }); // will print x, y, 23

Strings n n are sequences of Unicode chars (each char is 1 or 2

Strings n n are sequences of Unicode chars (each char is 1 or 2 UTF 16 code units) are objects which have methods: n n n n n char. At(index): return character from index concat(str): concatenate “str” to this string includes(str): searches “str” in this string starts. With(str), ends. With(str): check if this string starts/ends with index. Of(char): index of char in this string match(regex): check if regular expression matches this string replace(what, replace. With): replace in this string search(str): search string slice(begin. Index, end. Index): extract subsection of this string split(separator): return an array of strings by splitting this string

Collections (creation and iteration) n Creating arrays var array 1 = new Array(2, 3,

Collections (creation and iteration) n Creating arrays var array 1 = new Array(2, 3, 5); var array 2 = Array(“abc”, “de”, “fghij”); var array 3 = [0, “abc”, 2]; var array 4 = new Array(array. Length); var array 5 = Array(array. Length); n Array. length is the highest index + 1 (NOT the number of elements!) var a = [ 1, 2, 10]; a[20] = 11; console. log(a. length); // will print 21

Collections (Array methods) n n n concat() joins two arrays and returns a new

Collections (Array methods) n n n concat() joins two arrays and returns a new array join(delimiter = ', ') joins all elements of an array into a string push() adds one or more elements to the end of an array and returns the resulting length of the array. pop() removes the last element from an array and returns that element shift() removes the first element from an array and returns that element slice(start. Index, upto. Index) extracts a section of an array and returns a new array.

Collections (Array methods; cont. ) n n n splice(index, count. To. Remove, add. Element

Collections (Array methods; cont. ) n n n splice(index, count. To. Remove, add. Element 1, add. Element 2, . . . ) removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array reverse() transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array sort() sorts the elements of an array in place, and returns a reference to the array index. Of(search. Element[, from. Index]) searches the array for search. Element and returns the index of the first match for. Each(callback[, this. Object]) executes callback on every array item and returns undefined. map(callback[, this. Object]) returns a new array of the return value from executing callback on every array item

eval() n n eval(string) – if string is an expression, evaluates the expression and

eval() n n eval(string) – if string is an expression, evaluates the expression and if string is a sequence of javascript statements, it executes those statements Ex: eval(“ 2+3”) => 5 a=2; eval(“a+4”) => 6 eval("var x=2; console. log(x); ") => create global variable x=2 and print 2 on the console

Functions In Javascript, functions are first class citizens: • they can be saved in

Functions In Javascript, functions are first class citizens: • they can be saved in variables • they can be passed as parameters • they have properties, like other objects • they can be defined without an identifier

Functions n n usually they are declared in the <head> tag and called all

Functions n n usually they are declared in the <head> tag and called all over the html file the syntax of declaring a function is: function name_fct(parameters, arguments) { … statements … } where parameters represent specific parameters sent to the function, arguments contain a variable number of arguments; the variable arguments can be accessed inside the function through arguments[i], where i goes from 0 to arguments. length n n all primitive parameters are passed to the function by value; only object properties changes are visible outside the function (if param is an object) If no return is present, Javascript returns undefined

Functions. Rest parameters n another way of accessing a variable number of parameters: function

Functions. Rest parameters n another way of accessing a variable number of parameters: function f(x, y, …rest. Args) { for (let value of rest. Args) { …. } } f(1, 2, 3, 4, 5, 6); // x=1, y=2, rest. Args=[3, 4, 5, 6]

Function expressions n Function names can be used as arguments for other functions or

Function expressions n Function names can be used as arguments for other functions or values for variables function cubic(x) { return x*x*x; } var square. Func. Var = function square (x) { return x*x; } function map(f, a) { for(i=0; i<a. length; i++) { console. log(f(a[i])); } } var v = [ 1, 2, 3 ]; map(cubic, v); // will print 1, 8, 27 map(square. Func. Var, v); // will print 1, 4, 9

Creating functions using the Function constructor var sum = new Function(‘x’, ‘y’, ‘return x+y’);

Creating functions using the Function constructor var sum = new Function(‘x’, ‘y’, ‘return x+y’); sum(2, 3); § § § functions created with the Function() constructor do not create closures to their creation context, they are created in the global context they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called all functions are actually objects (of the prototype Function)

Anonymous functions Ex. 1: var square = function(a) { return a*a; } square(2); //

Anonymous functions Ex. 1: var square = function(a) { return a*a; } square(2); // calling the function Ex. 2: (function(a) { return a*a; }) (3); // this function is auto-called after the declaration; returns 9

Function scope n n variables defined inside a function can not be accessed outside

Function scope n n variables defined inside a function can not be accessed outside the function but a function can access all variables from the scope in which it is defined: n n n if the function is defined in global scope, it can access all variables defined in the global scope if the function is defined inside another function, it can access all variables (and parameters) defined by its parent function and all variables to which the parent function has access functions are hoisted (i. e. in the same file, they can be called before the line in which they are defined)

Inner functions and closures n n n a nested (inner) function can only be

Inner functions and closures n n n a nested (inner) function can only be accessed from statements in the outer function the inner function forms a closure: the inner function can use the parameters and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function a closure provides a form of encapsulation for the variables of the inner function

Closure example function outer(a, b) { var c = 3; function inner (x, y)

Closure example function outer(a, b) { var c = 3; function inner (x, y) { // a, b, and c are all accessible here x = x+y+c*(a+b); return x; } inner(a, b); }

Default parameters function sum(a, b = 0) { return a+b; } sum(2); // returns

Default parameters function sum(a, b = 0) { return a+b; } sum(2); // returns 2

Arrow function expressions (have shorter syntax) n n (param 1, param 2, …, param.

Arrow function expressions (have shorter syntax) n n (param 1, param 2, …, param. N) => { statements } (param 1, param 2, …, param. N) => expression equivalent to: => { return expression; } parentheses are optional when there's only one parameter name: (single. Param) => { statements } single. Param => { statements } n the parameter list for a function with no parameters should be written with a pair of parentheses: n () => { statements } n

Arrow function expressions (cont. ) var materials = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium']; console.

Arrow function expressions (cont. ) var materials = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium']; console. log(materials. map( m => m. length)); // will output: Array [8, 6, 7, 9]

Classes & Objects

Classes & Objects

Classes and objects n n n Js is a prototype-based language, it does not

Classes and objects n n n Js is a prototype-based language, it does not distinct between a class and a class instance (object); it only has objects; An object is an associative array (dictionary) augmented with a prototype Almost all objects in Javascript are instances of Object Javascript objects inherit properties and methods from Object. prototype (prototype is a property of Object) The prototype pattern implies creating a new object by cloning an existing one (a prototype) current object referred with this; inside a function, this refers to the object on which the function is called; if that object does not exist, this is the global object (i. e. the browser window)

Classes and object syntaxes n two syntaxes for working with objects in Javascript: n

Classes and object syntaxes n two syntaxes for working with objects in Javascript: n n Classical, functional: declare the properties and methods in a constructor-like function ES 6 syntax: introduced by ECMAScript 2015 (ES 6), uses class, extends, static, constructor similar to Java, C++

Objects. Creation, properties, methods n creating objects can be done in 3 ways: n

Objects. Creation, properties, methods n creating objects can be done in 3 ways: n using an object initializer: object. Name = {property 1: value 1, property 2: value 2, . . . , property. N: value. N} n using a constructor function (object prototype): function print() {…} function Thing(x, y, z) { this. prop 1=x; this. prop 2=y; this. prop 3=z; this. method 1=print; } ob = new Thing(a, b, c); n creating an empty object first and then adding properties to it: var person = new Object(); person. name=“Forest”; person. age=25; n n n objects are deleted using “delete object. Name” properties are accessible by obj. property or obj[index_property] or obj[“property”] new properties can be added to object on run-time: obj. new. Prop=val

Object creation (prototype ex. ) function say. Hi () { console. log(“This is student

Object creation (prototype ex. ) function say. Hi () { console. log(“This is student “+this. first. Name+” “ +this. last. Name); } function Student (first. Name, last. Name, year) { this. first. Name = first. Name; this. last. Name = last. Name; this. year = year; this. say. Hi = say. Hi; } var stud = new Student(“Adrian”, “Sterca”, 3); stud. say. Hi();

The ES 6 class syntactic sugar n n ECMAScript 2015 (ES 6) introduced syntactic

The ES 6 class syntactic sugar n n ECMAScript 2015 (ES 6) introduced syntactic sugar for defining classes, although the Javascript object model remained the same, prototypical. Ex. : class Student { constructor(first. Name, last. Name, year) { this. first. Name = first. Name; this. last. Name = last. Name; this. year = year; } } var stud = new Student(“Adrian”, “Sterca”, 3);

Class expressions just like function expressions let stud = class { // unnamed class

Class expressions just like function expressions let stud = class { // unnamed class n constructor(first. Name, last. Name, year) { this. first. Name = first. Name; this. last. Name = last. Name; this. year = year; } }; let stud = class Student { // named class constructor(name) { this. name = name; } };

Methods, static methods, setters & getters class Student { constructor(first. Name, last. Name) {

Methods, static methods, setters & getters class Student { constructor(first. Name, last. Name) { this. first. Name = first. Name; this. last. Name = last. Name; this. grades = [ ]; } // Getters & Setters are used to create pseudo-properties. You can't use them on a real property (specified in constructor). get study. Year() { return this. year; } // getter get specialization() { return this. spec; } // getter set study. Year(year) { this. year = year; } // setter set specialization(spec) { this. spec = spec; } // setter // method add. Grade(course, grade) { this. grades[course] = grade; } // static method static say. Hi(text) { console. log("This is a student. ", text); } } var stud = new Student("Adrian", "Sterca"); stud. first. Name="Forest"; stud. last. Name=""; study. Year=2; // calling setter stud. specialization="Info EN"; // calling setter stud. add. Grade("Web", 8); console. log(stud. first. Name+ " " +stud. last. Name + ": ", stud. grades); //stud. say. Hi("Hi"); // Error. Can not call static method on instance Student. say. Hi("Hi"); // properly calling static method

Methods (continuation) n inside class methods, you refer to members of the class (properties

Methods (continuation) n inside class methods, you refer to members of the class (properties or other methods) always using this. prefix: class Student { … transfer(faculty, specialization, year) { this. faculty = faculty; this. specialization = specialization; this. year = year; this. say. Hi(); } }

Public and private fields (experimental; a transpiler like Babel may be needed) class Student

Public and private fields (experimental; a transpiler like Babel may be needed) class Student { id = 0; grade; #first. Name; #last. Name; constructor (id, grade, first. Name, last. Name) { this. id = id; this. grade = grade; this. #first. Name = first. Name; this. #last. Name = last. Name; } }

Class inheritance class Person { constructor(first. Name, last. Name) { this. first. Name =

Class inheritance class Person { constructor(first. Name, last. Name) { this. first. Name = first. Name; this. last. Name = last. Name; } say. Hi(text) { console. log("This is " + this. first. Name + " " + this. last. Name + ". " + text); } } class Student extends Person { // inheritance constructor(first. Name, last. Name) { super(first. Name, last. Name); // calling constructor from base class this. grades = [ ]; } say. Hi(text) { super. say. Hi(); // calling method from base class console. log("I'm also a student"); } }

Predefined objects n n n n n Array, Map, Set – working with arrays,

Predefined objects n n n n n Array, Map, Set – working with arrays, maps and sets Boolean – true or false Function – specifies a string of code to be precompiled as a function Date – date functions Math – math functions Number – numerical constants and representations Reg. Exp – regular expressions String – string operations Symbol (new from ES 6) : used for identifying objects (mostly internal in the javascript engine)

Template literals n n Syntactic sugar that allows placing embedded expression into string constants

Template literals n n Syntactic sugar that allows placing embedded expression into string constants Template literals are written between `. . ` var name = “forest”; var str = `this is ${name}`; // variable replacement var str 1 = ‘ this is a multiline string`; var str 2 = `do the sum ${1+2+3}`; // computing arithmetic expression

The spread operator (…) var a = [1, 2, 3]; var b = […a,

The spread operator (…) var a = [1, 2, 3]; var b = […a, 4, 5, 6]; // b = [1, 2, 3, 4, 5, 6] var c = […a] ; // array copy var obj = { prop 1: 1; prop 2: "2"; } var objcopy = { …obj }; // object cloning var str = "hello"; var helloarray = [ …str]; // helloarray = [‘h’, ’e’, ’l’, ’o’] // calling a function with an array parameter: const f = (arg 1, arg 2) => {} const a = [1, 2] f(. . . a)

Destructing a = [1, 2, 3, 4, 5, 6]; [first, , third]=a; // first=1

Destructing a = [1, 2, 3, 4, 5, 6]; [first, , third]=a; // first=1 and third=3 const student = { first. Name: "Forest"; last. Name: " Forest"; age: 41 } const { first. Name: name, age: ageval } = student // name will be “Forest” and ageval will be 41 const { last. Name, age } = student

The strict mode n n the default running mode of javascript in browser is

The strict mode n n the default running mode of javascript in browser is a sloppy mode: non-critical errors are passed over, optimization is harder to achieve strict mode introduces some restrictions to the javascript engine: n n n eliminates some Java. Script silent errors by changing them to throw errors fixes mistakes that make your code harder to optimize by javascript engines prohibits the usage of some symbols maked as keywords in future versions of ECMAScript

Apply strict mode n n n strict mode can be applied to a whole

Apply strict mode n n n strict mode can be applied to a whole script or to a function (not to a block) to invoke strict mode, one needs to specify at the beginning of the script or function: ’use strict’; concatenating strict mode scripts with non-strict mode scripts can be tricky

Strict mode mistakes converted to errors ‘use strict’; mistype. Variable = 7; // if

Strict mode mistakes converted to errors ‘use strict’; mistype. Variable = 7; // if no global variable ‘mistype. Variable’ exists // (defined with “var”), this line throws // Reference. Error // Assignment to a non-writable global var undefined = 5; // throws a Type. Error var Infinity = 5; // throws a Type. Error var o = { p: 1, p: 2 }; // syntax error (redefinition of p) // reserved words: implements, interface, let, package, private, // protected, public, static, and yield

Javascript modules n n n as the javascript code run in the browser becomes

Javascript modules n n n as the javascript code run in the browser becomes larger and larger, module usage becomes important module files can be *. js or *. mjs it’s a good idea to serve modules from an http server (not from the local file system, file: //) so that you don’t run into CORS issues a module can export var, let, const, functions, classes – they all need to be in the global context a javascript code can import every exported symbol from a module or just some of them modules are imported into the scope of a single js script, they are not available in the global scope

Exporting symbols from a module n Consider the file module. js with the following

Exporting symbols from a module n Consider the file module. js with the following content: export const symbol 1 = “str”; export var symbol 2 = 3; export function do. Something(params) { …. } OR export { symbol 1, symbol 2, do. Something }; // at the end of file

Importing symbols from a module into a javascript file n in another module main.

Importing symbols from a module into a javascript file n in another module main. js, we import the symbols from module. js: import {symbol 1, symbol 2, do. Something } from ‘. /module. js’; OR import * from ‘. /module. js’; n in the. html file where we use main. js, we need to include it like this: <script type=“module” src=“main. js”></script>

Importing into module object import * as Module 1 from ‘. /modules/mod 1. js”;

Importing into module object import * as Module 1 from ‘. /modules/mod 1. js”; import * as Module 2 from ‘. /modules/mod 1. js”; … // calling functions from mod 1. js Module 1. function 1(); Module 1. function 2(); // calling functions from mod 2. js Module 2. function 1(); Module 2. function 2();

Dynamic module loading import('. /modules/my. Module. js'). then( (module) => { // Do something

Dynamic module loading import('. /modules/my. Module. js'). then( (module) => { // Do something with the module. // call functions });

Events n n Javascript is an event-based language Event: mouse click, key pressed, element

Events n n Javascript is an event-based language Event: mouse click, key pressed, element loosing focus etc. when an event is triggered by the browser a predefined or user-defined (in Javascript) event handler takes control event handlers are associated to a tag: 1) <TAG event. Handler=“Javascript code”> 2) <script type=“text/javascript”> function ev. Handle(x) { … } </script> <TAG event. Handler=“ev. Handle(this)”> 3) <script type="text/javascript"> obj. event. Handler=“Javascript code”; </script>

Selective list of Events A complete list of events is here: https: //www. w

Selective list of Events A complete list of events is here: https: //www. w 3 schools. com/jsref/dom_obj_event. asp

Javascript and HTML Js scripts can be used in HTML documents in 4 ways:

Javascript and HTML Js scripts can be used in HTML documents in 4 ways: 1) as instructions or functions written inside a <SCRIPT> tag: n <script type=”text/javascript”> … Java. Script statements. . . </script> 2) Js code written in a separate javascript file: <script src="common. js"></script> 3) using a Js expression as the value of an html attribute: <hr width="&{bar. Width}; %" align=“left"> <h 4>&{my. Title}; </h 4> Java. Script entities start with “&” and end with “; ” and are enclosed in “{}” 4) as an event handler: <input type="button" value="Press Me" on. Click="func()">

Good way of including. js in. html file the following line makes the browser

Good way of including. js in. html file the following line makes the browser run the js code in script. js only after the HTML document is completely loaded: <script src=“script. js” defer></script> n this is useful when: const button = document. query. Selector(“#button”); button. add. Event. Listener(‘click’, some. Function); If this script is placed in <head>, the browser throws an error because the <button id=“button”> is not loaded yet, “button” constant is null. n

Pop-up boxes n n n alert(“…text…”) : displays text and the Ok button confirm(“…

Pop-up boxes n n n alert(“…text…”) : displays text and the Ok button confirm(“… text…”) : displays text and returns true if the Ok button is clicked and false if the Cancel button is clicked prompt(“text”, “default value”): the user can enter an input value and then click Ok (return the value) or Cancel (return null)

Document Object Model (DOM)

Document Object Model (DOM)

DOM (Document Object Model) n n n is a standardized (by W 3 C)

DOM (Document Object Model) n n n is a standardized (by W 3 C) hierarchical model of an HTML or XML document DOM can be used for navigating in the document structure, modify the document structure (add, delete, modify child elements etc. ) and also modifying attributes of an element each tag is a DOM object it has an API which can be used in Javascript + DOM is sometimes called DHTML (Dynamic HTML)

Hierarchical DOM structure Copyright: Birger Eriksson; Wikipedia

Hierarchical DOM structure Copyright: Birger Eriksson; Wikipedia

DOM Browser Objects n n n Window object Navigator object Screen object History object

DOM Browser Objects n n n Window object Navigator object Screen object History object Location object

DOM document objects n n n n Document object Anchor object Area object Base

DOM document objects n n n n Document object Anchor object Area object Base object Body object Button object Event object Form object Frameset object IFrame object Image object Input Button object Input Checkbox object Input File object n. Input Hidden object n. Input Password object n. Input Radio object n. Input Reset object n. Input Submit object n. Input Text object n. Link object n. Meta object n. Object object n. Option object n. Select object n. Style object n. Table. Cell object n. Table. Row object n. Textarea object

Document object collections Collection Description forms[] Returns a reference to all Form objects in

Document object collections Collection Description forms[] Returns a reference to all Form objects in the document images[] Returns a reference to all Image objects in the document links[] Returns a reference to all Area and Link objects in the document anchors[] Returns a reference to all Anchor objects in the document

Document object properties Property Description body Gives direct access to the <body> element cookie

Document object properties Property Description body Gives direct access to the <body> element cookie Sets or returns all cookies associated with the current document domain Returns the domain name for the current document last. Modified Returns the date and time a document was last modified referrer Returns the URL of the document that loaded the current document title Returns the title of the current document URL Returns the URL of the current document

Document object methods Method Description close() Closes an output stream opened with the document.

Document object methods Method Description close() Closes an output stream opened with the document. open() method, and displays the collected data get. Element. By. Id() Returns a reference to the first object with the specified id get. Elements. By. Name() Returns a collection of objects with the specified name get. Elements. By. Tag. Name() Returns a collection of objects with the specified tagname open() Opens a stream to collect the output from any document. write() or document. writeln() methods write() Writes HTML expressions or Java. Script code to a document writeln() Identical to the write() method, with the addition of writing a new line character after each expression

The Element Object. Properties n n n n n a DOM Element represents an

The Element Object. Properties n n n n n a DOM Element represents an HTML tag. attributes - returns a map of all attributes of this elem. . children – returns a collection of children of this elem. . class. List – returns all classes of this element. class. Name – set/get the class attribute of this elem. . client. Height, . client. Width - returns height/width including padding. first. Child - returns first child node. first. Element. Child – returns first child element (ignores text and comments). inner. HTML, . inner. Text – set/get the content of this elem. . id – set/get the ID attribute of this element

The Element Object. Properties (2) n n n n . last. Child - returns

The Element Object. Properties (2) n n n n . last. Child - returns the last child node of this elem. . last. Element. Child - returns the last child element of this elem. (ignores text and comments). next. Sibling, . previous. Sibling - returns the next/prev node at the same level. next. Element. Sibling, . previous. Element. Sibling – returns the next/prev element at the same level (ignores text and comments). parent. Node - returns the parent node of this element. parent. Element – returns the parent element of this element (ingnores text and comments). style – set/get the style attribute of this element

The Element Object. Methods n n n n n add. Event. Listener(), remove. Event.

The Element Object. Methods n n n n n add. Event. Listener(), remove. Event. Listener() – adds/removes an event listener for this elem. append. Child(), remove. Child() – append/remove a child to this element click() – simulates a mouse click on this elem. get. Attribute(), set. Attribute() – get/set attribute get. Elements. By. Tag. Name() – returns children by tag name get. Elements. By. Class. Name() – returns children by class name insert. Before() – insert a new child node before existing child node of this element remove() – remove this element query. Selector() - returns the first child that matches a selector query. Selector. All() – return all children that match a selector

document. query. Selector() n document. query. Selector(selector) : returns the first element that matches

document. query. Selector() n document. query. Selector(selector) : returns the first element that matches the CSS “selector” list; Ex. : document. query. Selector(“#first”); n document. query. Selector. All(selector) : returns all elements that matches the CSS “selector” list; Ex. : document. query. Selector. All(“. first, p. second”);

Creating & removing elements (tags) dynamically var p = document. create. Element(“p”); // create

Creating & removing elements (tags) dynamically var p = document. create. Element(“p”); // create “p” tag var text = document. create. Text. Node(“text content”); p. append. Child(text); // append text to tag “p” p. inner. HTML = “other text”; // set a new content text var p 1 = p. clone. Node(); // create copy of p p. insert. Before(p 1); // add another element before p. remove. Child(p. first. Child); p. remove(); // remove first child of p // remove p (the element itself)

Modifying elements (tags) var section = document. query. Selector(“section”); section. set. Attribute(“class”, “red-section”); section.

Modifying elements (tags) var section = document. query. Selector(“section”); section. set. Attribute(“class”, “red-section”); section. style. background = “red”; section. inner. HTML = “<p>test</p>”; section. inner. Text = “test”;

Asynchronous programming var timeout. ID = window. set. Timeout(func, delay, [param 1, param 2,

Asynchronous programming var timeout. ID = window. set. Timeout(func, delay, [param 1, param 2, . . . ]) Calls function “funct” with the specified parameters after “delay” miliseconds have passed. n window. clear. Timeout(timeout. ID); Clears the timeout (async function is no longer called). n

Asynchronous programming (promises) const my. First. Promise = new Promise(function (resolve, reject) { //

Asynchronous programming (promises) const my. First. Promise = new Promise(function (resolve, reject) { // do something asynch which eventually calls either: // resolve(some. Value); // fulfilled // or // reject("failure reason"); // rejected }); The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object); the resolve and reject functions are provided by the Javascript engine. The resolve and reject functions, when called, resolve or reject the promise, respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.

Getting result from a promise // Promises can not return anything, they just pass

Getting result from a promise // Promises can not return anything, they just pass results to callbacks (which are specified with. then()) const p = new Promise(function(resolve, reject) { // the asynchronous word - just a console. log() console. log("Doing some work. . . "); resolve("Done"); }); // without. then() you can not get the result from the Promise // we assume the Promise p is always resolved p. then(function(result) { console. log(result); // just print the returned result of the Promise })

Javascript and browser compatibility n n browser compatibility is and issue even outside javascript

Javascript and browser compatibility n n browser compatibility is and issue even outside javascript (html, css) -> different browser show tags differently (i. e. have default styles) => the need to reduce browser inconsistencies (CSS reset or reboot packages) with javascript/ECMAScript, some browser implement a version of ECMAScript, other browser implement other ECMAScript versions => the need to use polyfills (js libraries that extend the functionality of the browser): Core-js, Polyfill. io and transpilers (e. g. Babel – takes a higher ECMAScript version code and converts it into a lower ECMAScript version code)

Javascript quirks Javascript can be a very powerful language, a messy one, a language

Javascript quirks Javascript can be a very powerful language, a messy one, a language full of drama … Here is a small list of javascript quirks (larger list is here: https: //dev. to/mkrl/javascript-quirks-in-one-image-from-the-internet-52 m 7 ): 0. 5+0. 1==0. 6 -> true 0. 2+0. 1==0. 3 -> false typeof(Na. N) -> number 3+” 1” -> “ 31” 10 -” 1” -> 9 true===1 -> false true==1 -> true [ ]+[ ] -> “”

Browser API, Web API, Js libraries, Js frameworks n n Browser API – a

Browser API, Web API, Js libraries, Js frameworks n n Browser API – a set of javascript functions, objects & properties exposed by the browser; e. g. DOM; a list of browser APIs developed by w 3 c. org is here: https: //www. w 3. org/standards/techs/js#w 3 c_all Web API – a server-side API usually exposed through HTTP requestresponse; the response is usually a JSON expression Js library – one or more js files providing custom functions & objects that enhance the functionality of the javascript language; e. g. j. Query Js framework – a js library plus html & css code used to write an entire web application from scratch; inversion of control – key difference between libraries and frameworks: when calling a method from a library, the developer is in control; with frameworks control is inverted – the framework calls developer’s code; e. g. angular js

Js debugging tools n n n Firefox’s Web Console and Chrome’s Inspector Js. Fiddle

Js debugging tools n n n Firefox’s Web Console and Chrome’s Inspector Js. Fiddle (https: //jsfiddle. net/) Code. Pen (https: //codepen. io)

Additional Documentation n n http: //www. cs. ubbcluj. ro/~forest/wp http: //www. w 3 schools.

Additional Documentation n n http: //www. cs. ubbcluj. ro/~forest/wp http: //www. w 3 schools. com/js/default. asp http: //www. w 3 schools. com/jsref/dom_obj_document. asp https: //developer. mozilla. org/en/Java. Script https: //babeljs. io/docs/en/learn