An online markdown blog and knowledge repository.
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
key:value
pairs: Property name is the Key, and the property value is the Value.key:value
pairs: Method name is the Key, the Function definition is the value.Create an object using Literal Notation [Duckett, pg.102]
var hotel = {
name: 'Quay',
rooms: 40,
booked: 25,
checkAvailability: function() {
return this.rooms - this.booked;
}
}
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;
// 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);
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;
There are three primary types of objects:
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.
Duckett Pgs.128,129 has a large table of many String properties and how to use them.
Primitive Data Types:
Complex Data Types:
Overview:
Think of this like an 'Org Chart' of a web page.
Recall that all object will have their own set of Properties and Methods.
You must select an Element Node before gaining access to the other Node types:
Once selected, elements can be manipulated:
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');
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).
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.
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.
Repeat the same action on every Node in a NodeList using Looping structures.
Walk the tree through element types using the following properties:
parentNode
: The Node that contains the currently selected Node.previousSibling
and nextSibling
: The next or previous Node that shares the exact same Parent Node.firstChild
and lastChild
: The first or last child node to the currently selected Node.Most browsers count whitespace as individual Nodes, sibling to other text, inline, or block level nodes.
From [Duckett, pg.214]:
document.getEleemntById('one').firstChild.nextSibling.nodeValue;
<li>
is the <em>
element.<em>
element.Key Takeaway: Use 'nodeValue' to access and update text in nodes, either within a selector or through custom variables.
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]:
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:
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'
Add Process Overview:
createElement()
method into a new variable.createTextNode()
.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:
.gtElementsByTagName('p')[0]
.parentNode
method of the variable created in step 1, above..removeChild()
function and include the variable of the element to be removed.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.
Using innerHtml
calls can allow an attacker access to the DOM, Cookies, and Session Tokens.
To ward against XSS attacks:
Always validate user input.
Always control where content goes.
Escape user content at the server, i.e. /&
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.
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.
Open "Developer Tools" in the browser and select the "Elements" tab or view to see the full DOM Tree.