Reading notes for Code Fellows!
Many problem domains we face as programmers are difficult to understand. Often, these problem domains also look completely different depending on individual viewpoints.
Programmers are also routinely not given complete information about the problem domain, whihch leads to the issue of not even having the information needed to understand it.
When the problem domain is understood, dlear and concise, writing the code becomes far easier.
Understanding is the most critical piece…
Coversely, it is difficult to solve a problem before you know what the question is.
We can do one of two things:
It may take a little more time and money to invest in understanding, but it cost significantly more to have to do things over rather than get them right the first time.
Objects group together a set of variables and functions to create a model of something. In an object, variables and functions take on new names. In an object:
In JavaScript:
Literal notation is the easiest and most popular way to creat objects. The object is the set of keys and values inside a set of curly braces. It is stored in a variable.
var hotel = {
name: 'Quay',
rooms: 40,
booked: 25,
checkAvailability: function() {
return this.rooms - this.booked;
}
};
When creating an object:
checkAvailability()
method above, the this keyword is used to indicate that it is using the rooms and booked properties of this object.We can access the properties or methods of an object using dot notation. We can also access properties using square brackets. To access properties of methods of objects, we use the name of the object followed by a period and then the name of the property or method we want to access. This is called dot notation. The period is known as the member operator.
var hotelName = hotel.name;
We can also access the properties or methods using square bracket syntax.
var hotelName = hotel['name'];
This notation is most commonly used when:
Functions that are used as methods of an object can still have parameters. When called as methods, arguments are passed to the method just like when we call a regular function.
The Document Object Model (DOM)specifies how browsers should create a model of an HTML page and how JavaScript can access and update the contents of a web page while it is in the browser. It is neither part of HTML, nor part of JavaScript, but rather a separate set of rules. These rules cover two primary areas:
As a page loads, the browser creates a DOM Tree model of that page which it stores in its memory. These models consist of four main types of nodes. Each node is an object with properties and methods. Scripts access and update the DOM tree and make changes to only the DOM tree whcih are then reflected in the browser. The source HTML file remains unaltered. The four types of nodes are:
An overview of the two types of methods and properties that access elements, DOM Queries and traversing the DOM:
getElementById()
- Usesthe value on an element’s id
attributequerySelector()
- Uses a CSS selector, and returns the first matching elementparentNode
- Selects the parent of the current element nodepreviousSibling
/ nextSibling
- selects the previous or next sibling from the DOM treefirstChild
/ lastChild
- Selects the first or last child of the current elementgetElementsByClassName()
- Selects all elements that have the specified value for their class attributegetElementsByTagName()
- Selects all elements that have the specified tag namequerySelectorAll()
- Uses a CSS selector to select all matching elementsWhen people say the DOM is working with an element, it is actually working with the node that represents that element. Sample methods and properties that work with the elements:
nodeValue
- This property lets us access or update contents of a text node..innerHTML
- A propetry that allows access to child elements and text contenttextContent
- A property that allows access to only the text contentcreateElement()
createTextNode()
appendChild()
removeChild()
className
/ id
- (properties) Lets us get or update the value of these attributeshasAttribute()
- (method) Checks if an attribute existsgetAttribute()
- (method) Gets the value of an attributesetAttribute()
- (method) Updates the valueremoveAttribute()
- (method) removes the attributeMethods that find elements in the DOM a DOM queries. When we need to work with an element more than once, we should cache the reference location of the element in a variable:
var itemOne - getElementById('one');
DOM queries can return a single element or a NodeList, which is a group of elements. These node lists are collections of nodes and they are similar to arrays in that they are 0-indexed lists.
getElementById('id')
- selects an individual element given the value of its id attribute.querySelector('css selector')
- uses CSS selector syntax that would select one or more elements. This method returns only the first of the matching elements.getElementsByClassName('class')
- selects one or more elements given the value of their class attribute. This method is faster than querySelectorAll()
.getElementsByTagName('tagName')
- selects all elements on the page with the specified tag name. This method is faster than querySelectorAll()
.querySelectorAll('css selector')
- uses CSS selector syntax to select one or more elements and returns all of those that match.getElementById()
and querySelector()
both use similar syntax and search an entire document and return individual elements. getElementById()
is the quickest and most efficient way to access an element. querySelector()
is very flexible because its parameter is a css selector and therefore it can target many more elements.
document.getElementById('one')
document
refers to the document object, which must be accessed in order to access elements.
.
is the member operator - “dot notation”.
getElementById()
is the method being employed.
'one'
is the parameter of the method.
NodeLists look like arrays and are number like arrays, but they are not actually arrays. They are a type of object called a collection. Properties and methods exist for NodeLists, notably:
length
list the number of items in the NodeListitem()
returns a specific node from the Nodelist when we supply the index number of the item we want. It is not uncommon to use square-bracket array notation when retrieving these items from the list however.Example DOM queries that return NodeLists:
getElementsByTagName()
getElementsByClassName()
querySelectorAll()
There are two ways to select an element from a NodeList: The item()
method and array syntax. Both require the index number of the desired element. Array syntax is preferred over the item()
method however because it is faster. Store the NodeList in a variable if it will be repeatedly used.
var elements = document.getElementsByClassName('hot');
if (elements.length >= 1) {
var firstItem = elements[0];
}
if
statementWe can loop through each node in a NodeList and apply the same statements to each. For instance the following gathers all list items with a class attribute of ‘hot’ and changes them to ‘cool’.
var hotItems - document.querySelectorAll('li.hot');
for (var i = 0; i < hotItems.length; i++) {
hotItems[i].className = 'cool';
}
Five properties can be used on an element to select another element with respect to the current element. This is known as traversing the DOM.
parentNode
previousSibling
nextSibling
firstChild
lastChild
There are two different approaches to adding and removing content from a DOM tree. the innerHTML
property and DOM manipulation. There are security risks associated with innerHTML
but is is faster and better suited to updating entire fragments. DOM manipulation can be safer, but it requires more code and can be slower by comparison, but it easily targets individual nodes in the DOM.
innerHTML
PropertyinnerHTML
can be used on any element node to either retrieve or replace content. The content is provided as a string and can include markup.
DOM manipulation refers to a set of methods that allow us to create element and text nodes and then attach them to or remove them from the DOM tree.
document.write()
element.innerHTML
DOM Manipulation
innerHTML
when a lot of changes to content must be madeinnerHTML
Once we have an element node, we can us other properties and methods to access and alter its attributes. For instance:
document.getElementById('one').getAttribute('class');
Sample methods than can be used to manipulate these values:
Method/Property | Description |
---|---|
getAttribute() |
gets the value of the attribute |
hasAttribute() |
checks if the element node has a specified attribute |
setAttribute() |
sets the value of an attribute |
removeAttribute() |
removes an attribute from an element node |
className |
gets or sets the value of the class attribute |
id |
gets or sets the value of the id attribute |