reading-notes

Reading notes for Code Fellows!


Project maintained by William-Moreno Hosted on GitHub Pages — Theme by mattgraham

Problem Domain, Objects and the DOM


Understanding Problem Domains

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.

Programming Is Easy If You Understand…

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.

What can we do?

We can do one of two things:

  1. Make the Problem Domain easier, simpler, less complex, etc.
    • The domain can sometimes be made easier by cutting out cases and narrowing focus to a smaller piece of the problem.
  2. Get better at understanding Problem Domains.
    • We can become better at understanding problem domains, and avoid rushing to start coding before we thoroughly understand enough of the problem domain.

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.

JavaScript Objects

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:

Creating an Object: Literal Notation

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:

Accessing an Object and ‘Dot Notation’

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:

  1. THe name of the property or method contains special characters
  2. The name of the property is a number (technically allowed, but should be avoided).
  3. A variable is being used in place of the property name

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.

Document Object Model

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:

  1. Making a model of the HTML page. Using the DOM Tree model the DOM specifies the way in which the browser should construct the model out of object components.
  2. Accessing and changing the HTML page. THe DOM defines methods and properties to access and update the various objects within its model. This updates what is displayed in the actual browser. The DOM is often called an Application Programming Interface or (API). Through this, set the rules for what our script can ask the browser about the current model/page, and what it can tell the browser to update on that model/page.

The DOM Tree

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:

Working with the DOM Tree (2 - Steps)

  1. Locate the node that represents the element we want to work with.
  2. Use its text content, child elements and attributes.

Step 1: Access the Elements

An overview of the two types of methods and properties that access elements, DOM Queries and traversing the DOM:

Step 2: Working with Those Elements

When 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:

Caching DOM Queries

Methods 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');

Accessing Elements

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.

Methods that Return a Single Element Node

Methods that Return One or More Elements as a Nodelist

Selecting Individual Elements

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

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:

Example DOM queries that return NodeLists:

Selecting Elements from NodeLists

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];
}
  1. a NodeList containing elements with a class value of hot is created and stored in a variable called elements
  2. if there are at least one values in the NodeList, run the code in the if statement
  3. get the first element from the NodeList ([0])

Repeating Actions for an Entire NodeList

We 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';
}

Traversing the DOM

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.

  1. parentNode
  2. previousSibling
  3. nextSibling
  4. firstChild
  5. lastChild

Adding and Removing HTML Content

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 Property

innerHTML can be used on any element node to either retrieve or replace content. The content is provided as a string and can include markup.

  1. Create a variable holding the markup
  2. Select the element whose content you want to update
  3. Update content of selected element with the new markup

DOM Manipulation Methods

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.

  1. Create new text node
  2. Create new element node
  3. Add text node to element node
  4. Select element you want to ad the new fragment to
  5. Append the new fragment to the selected element

Three Techniques for Adding HTML to a Web Page.

document.write()

element.innerHTML

DOM Manipulation

Attribute Nodes

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

Back to Main