Week 4

Plan for the week

Examples

Resources

Objects

Objects

Objects are a very important data type in javascript. Objects can be stored in variables like other data types, and they themselves can contain more values as key value pairs. Here's an example of assigning an object to a variable:

var myPerson = {
  firstName: null,
  lastName: null
};

Object values can be accessed using a period (.), like so:

console.log(myPerson.firstName);

Objects can even contain code in the form of functions. Here's an example of how you can add a function to the above object:

myPerson.getFullName = function() {
  return this.firstName + ' ' + this.lastName;
};

this in the above example is a very special variable in javascript. In this case it refers to the object myPerson because the function is attached to that object.

DOM Manipulation

"DOM manipulation" is a term used to describe how we change a web page document using javascript. "DOM" stands for "Document Object Model", which really just refers to the page's document tree (something we've worked with a lot so far).

A browser tab always includes a few important objects that you'll need to know about in order to manipulate the DOM:

Here's an example of how you could use the functions listed above to add a link to a page:

// get the body element
var body = document.querySelector('body');
// create an anchor element var anchor = document.createElement('a');
// set the href and text of the anchor element anchor.setAttribute('href', 'http://avandamiri.com/fewd-37/'); anchor.textContent = 'FEWD-37';
// add the anchor element to the body body.appendChild(anchor);

In-Class Photos