Jon Rumsey

An online markdown blog and knowledge repository.


Project maintained by nojronatron Hosted on GitHub Pages — Theme by mattgraham

Notes from Duckett HTML and JS Books

Notes taken from Ducketts JavaScript and JQuery book while skimming Chapters 3 and 5.

JS Chapter 3 Functions Methods and Objects JS Chapter 5 Document Object Model

Chapter 3: Functions Methods and Objects (pg.100)

Introduction

Literal Notation

Create an object using Literal Notation [Duckett, pg.102]

var hotel = {
  name: 'Quay',
  rooms: 40,
  booked: 25,
  checkAvailability: function() {
    return this.rooms - this.booked;
  }
}

Accessing An Object

After creating a new object, access the object properties using dot notation:

let totalRooms = hotel.rooms;

Do the same to access Methods:

let currentAvailableRooms = hotel.checkAvailability();

The dot is known as a member operator.

Property access is also allowed through square bracket syntax, but not Methods:

let bookedRooms = hotel[rooms];

Objects can also be created using Constructor Notation:

let car = new Object();
car.color = "blue";
car.speed = 0;
car.model = "civic";
car.speedUp = function() {
  this.speed++;
};

Note: Using Constructor notation to add or remove objects only impacts the named instantiated object.

Property values can also be updated using Square Bracket Notation:

hotel[rooms] = 52;

Templating Object Creation

  1. Create a function that has arguments representing the object properties.
  2. Use Literal Notation to assign the arguments to properties, and define the object method(s).
  3. Assign the template to a new Pascal-case variable using the new keyword and supply the necessary argument values.
  4. The resulting variable will be the new object.
//  using literal notation to assign arg to props
function Hotel (name, rooms, booked) {
  this.name: 'Quay';
  this.rooms: 40;
  this.booked: 25;
  this.checkAvailability: function() {
    return this.rooms - this.booked;
  };
}

//  using the object template to create new instance
let snoqualmieHotel = new Hotel("Snoqualmie Falls Lodge", 20, 11);
let tulalipHotel = new Hotel("Tulalip Hotel", 235, 287);

Adding and Removing Properties

Add properties by using the following notation:

snoqualmieHotel.className = 'address' = "123 Summit Lane, Snoqualmie, WA";

Remove properties by using the 'delete' keyword:

delete snoqualmieHotel.address;

Keyword 'this'

About Objects

There are three primary types of objects:

  1. Browser Object Model: Has many child objects, properties, and other members.
  2. Document Object Model: Each element is stored in an object, and attributes are stored as object properties.
  3. Global Javascript Objects: String; Number; Boolean; Date; Math; Regex; etc.

Object Model Members

Browser Object Model:

Duckett Pg.124 has a listing of Browser Object Model properties and methods.

Document Object Model:

Duckett Pg.126 has a listing of Document Object Model properties and methods.

Note: If you use a member, like Alert(), and do not specify the model, Browser object will be called by default.

Global JS Objects

Duckett Pgs.128,129 has a large table of many String properties and how to use them.

Working With Data Types

Primitive Data Types:

Complex Data Types:

Chapter 5: Document Object Model (pg.183)

Overview:

DOM Tree

Think of this like an 'Org Chart' of a web page.

Recall that all object will have their own set of Properties and Methods.

Working With The DOM Tree

You must select an Element Node before gaining access to the other Node types:

  1. Using single-select techniques: getElementById() or querySelector()
  2. Using select-multiple techniques: getElementsByClassNam(), getElementsByTagName(), or querySelectorAll()
  3. Using Tree Traversal: parentNode, previousSibling, nextSibling, firstChild, lastChild

Once selected, elements can be manipulated:

  1. Text is stored in Text Nodes. Access it through firstChild property and then nodeValue to get the value.
  2. Access Text Nodes through innerHTML and textContent.
    2a. Create content: createElement(), createTextNode(), appendChild()
    2b. Remove content: removeChild()
  3. Attributes are accessed and updated via hasAttribute(), getAttribute(), setAttribute(), and removeAttribute()

Note: Text Node is a dead-end leaf. To get to child-element text, access must be made through the parent node(s).

Use variables to store elements and values that will be used more than once.

let fooElement = getElementById('foo');

Accessing Elements

A DOM Query will return a collection of results, even if only one element was found.
Use bracket (index) syntax to access the disired element.
Always use the "fastest route" to the element you seek, to keep the UI responsive and appear "fast".

DOM Query Getters that return a single element:

DOM Query Getters that return a NodeList:

Note: Again, browser support will vary, but document.getElementById('id'); is recommended (been around the longest).

Live and Static Node Lists

Using getElementsBy... is quicker and automatically updates your stored nodeLists.
Using querySelector... is slower and stored nodeLists are not udpated automatically.

Live: Select one or multiple elements using getElementsByTagName('tagName');, getElementsByClassName('className');.
Static: Select all elements at a level in the DOM using querySelectorAll('element[id]');.

Note: Elements returned by dynamic DOM Queries appear in the collection in the same order they appear in the DOM Tree.

Elements Within a NodeList

The item() method: Returns individual node within a NodeList, similar to Indexing but uses parentheses instead of brackets.
Using array syntax: Index into the NodeList using square brackets.

Looping Through a NodeList

Repeat the same action on every Node in a NodeList using Looping structures.

Traversing the DOM

Walk the tree through element types using the following properties:

Whitespace Nodes

Most browsers count whitespace as individual Nodes, sibling to other text, inline, or block level nodes.

Access and Update Text Using NodeValue

From [Duckett, pg.214]:

document.getEleemntById('one').firstChild.nextSibling.nodeValue;
  1. The 'li' element is selected using getElemntById().
  2. First Child of <li> is the <em> element.
  3. The text node is the next sibling of that <em> element.
  4. (...) access contents using nodeValue.

Key Takeaway: Use 'nodeValue' to access and update text in nodes, either within a selector or through custom variables.

Adding and Removing HTML Content

The DOM allows adding and removing Nodes. Use 'innerHTML' property to do this. Can be used on any Element Node to ADD or REPLACE content.
String content can include descendant element HTML markup.

Adding Content Process [Duckett, pg.218]:

  1. Store new content (including markup) as a string in a variable.
  2. Select the element whose content you wnat to replace.
  3. Set the element's innerHTML property to be the new string.

Remove Content Process [Duckett, pg.218], depending on the type:

To put changes to the DOM Tree, use separate methods to prepare-and-set the Node(s), one at a time:

  1. Capture or create Node content.
  2. Attach a Node to the correct spot in the DOM Tree.

For Removal, just use a single method, separate from the add and edit methods.

Get/Set Examples:

var foo = document.getElementById('bar').innerHTML; //  GETs the HTML from element ID 'bar'
document.getEleementById('doh').innerHtml = foo;      //  SET element with ID 'doh' with value of variable 'foo'

Adding and Removing Elements Using DOM Manipulation

Add Process Overview:

  1. Create and store a new element node with createElement() method into a new variable.
  2. Add a TextNode with text content using createTextNode().
  3. Append the TextNode to the new element Node using appendChild().

Note: Duckett recommends against leaving empty elements in the HTML for later updating by javascript code.

Elements are targeted by createElement() using the string name e.g. <p> would be 'p' in the parameter.

.appendChild() expects an Element type object as its parameter.

Remove Element Process Overview:

  1. Select the element to be removed using a DOM function like .gtElementsByTagName('p')[0]
  2. Select the parent node using .parentNode method of the variable created in step 1, above.
  3. Call the parent Node's .removeChild() function and include the variable of the element to be removed.

Updating HTML Content

Document Write method: document.write(). Only works during page load but is fast.
Element InnerHtml method: element.innerHtml. Good for adding lots of elements to a page, and to remove lots of content by assigning a blank string as a value. Do not use to replace user-added-content (like a form). Using it could break event handlers. DOM Manipulation Methods: Best for changing DOM element(s), will not break event handlers. Requires a lot of code. InnerHtml is faster.

Cross-Site Scripting Attacks

Using innerHtml calls can allow an attacker access to the DOM, Cookies, and Session Tokens.

To ward against XSS attacks:

  1. Validate user input, and filter out unwanted or unnecessary characters.
  2. Use server-side validation before submitting to the DB or displaying user data.
  3. DBs can safely store code and markup from "trusted sources" but not outside code.
  4. Filter outgoing content to remove potentially dangerous characters.
  5. Carefully control what content users can add to the page.
  6. DOM fragments from outside sources should be ignored.

Always validate user input.

Always control where content goes.

Escape user content at the server, i.e. /&amp and /+ (js) so it is not processed as executable code.

JQuery language constructs should also be escaped so they are not processed on the server side.

Always control all markup and code that is entered into and read from .innerHtml property and jQuery.html() method.

Attribute Nodes

Attributes can be changed on element nodes once a reference to them is made:

document.getelementById('header').getAttribute('for');

List of Methods and Properties:

getAttribute(): Returns attribute value.
hasAttribute(): Specified attribute exists on the element.
setAttribute(): Assigns a value to the selected attribute.
removeAttribute(): Deletes the attribute from the element Node.
className: Getter/Setter of class attribute name.
id: Getter/Setter of id attribute value.

Examining The DOM

Open "Developer Tools" in the browser and select the "Elements" tab or view to see the full DOM Tree.