GDI logo

JavaScript for Beginners

Class 3

Objects

Objects let us store a collection of properties.


var objectName = {
  propertyName: propertyValue,
  propertyName: propertyValue,
  ...
};
			  

var aboutMe = {
  hometown: 'Atlanta, GA',
  hair: 'Auburn',
  likes: ['knitting', 'code'],
  birthday: {month: 10, day: 17}
};
			  

Accessing Objects

You can retrieve values using "dot notation"


var aboutMe = {
  hometown: 'Atlanta, GA',
  hair: 'Auburn'
};
var myHometown = aboutMe.hometown;
			  

Or using "bracket notation" (like arrays)


var myHair = aboutMe['hair'];
			  

Changing Objects

You can use dot or bracket notation to change properties


var aboutMe = {
  hometown: 'Atlanta, GA',
  hair: 'Auburn'
};
aboutMe.hair = 'blue';
			  

Add new properties


aboutMe.gender = 'female';
			  

Or delete them


delete aboutMe.gender;
			  

Arrays of Objects

Since arrays can hold any data type, they can also hold objects


var myCats = [
  {name: 'Lizzie',
   age: 18},
  {name: 'Daemon',
   age: 1}
];

for (var i = 0; i < myCats.length; i++) {
  var myCat = myCats[i];
  console.log(myCat.name + ' is ' + myCat.age + ' years old.');
}
			  

Arrays of Objects

Just like other data types, objects can be passed into functions:


var lizzieTheCat = {
  age: 18,
  furColor: 'grey',
  likes: ['catnip', 'milk'],
  birthday: {month: 7, day: 17, year: 1996}
}

function describeCat(cat) {
  console.log('This cat is ' + cat.age + ' years old with ' + cat.furColor + ' fur.');
}

describeCat(lizzieTheCat);
			  

Let's Develop It

Create an object to hold information on your favorite recipe. It should have properties for recipeTitle (a string), servings (a number), and ingredients (an array of strings).

Try displaying some information about your recipe.

Bonus: Create a loop to list all the ingredients.

Object methods

Objects can also hold functions.


var lizzieTheCat = {
  age: 18,
  furColor: 'grey',
  meow: function() {
    console.log('meowww');
  },
  eat: function(food) {
    console.log('Yum, I love ' + food);
  },
};
			  

Call object methods using dot notation.


lizzieTheCat.meow();
lizzieTheCat.eat('brown mushy stuff');
			  

Built-in methods

JS provides several built-in objects:

Review: Anatomy of a website

Your Content
+ HTML: Structure
+ CSS: Presentation
= Your Website

A website is a way to present your content to the world, using HTML and CSS to present that content & make it look good.

IDs vs. Classes

ID -- Should only apply to one element on a webpage. For instance, a webpage only has one footer.

The "#" is how you tell CSS "this is an id."

Class -- Lots of elements can have the same class. For instance, there can be many warnings on one webpage.

The "." is how you tell CSS "this is a class name."

The DOM Tree

We model the nested structure of an HTML page with the DOM (Document Object Model) Tree. The browser makes a "map" of all the elements on a page.

The DOM: Sample Code


<!DOCTYPE html>
<html>
    <head>
        <title>Test Page</title>
        <style>
            h1 {
             color: red;
            }
        </style>
    </head>
    <body>
        <h1>My Page</h1>
        <p>Hello World!</p>
        <img src="http://placekitten.com/200/300" alt="cat"/>
    </body>
</html>
				

The DOM: Sample Model

Simple DOM Tree

DOM Access

Your browser automatically builds a Document Object to store the DOM of a page. To change a page:

  1. Find the DOM node and store it in a variable
  2. Use methods to manipulate the node

DOM Access: By Id

You can find nodes by id using the method:


document.getElementById(id);
			  

To find:


<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
			  

We would use:


var imgKitten = document.getElementById('kittenPic');
			  

DOM Access: By Tag Name

You can find certain types of HTML elements using this method:


document.getElementsByTagName(tagName);
			  

To find:


<li>Daisy</li>
<li>Tulip</li>
			  

We would use:


var listItems = document.getElementsByTagName('li');
for (var i = 0; i < listItems.length; i++) {
  var listItem = listItems[i];
}
			  

DOM Access: HTML 5

In newer browsers, you can use other methods too.

Available in IE9+, FF3.6+, Chrome 17+, Safari 5+:


document.getElementsByClassName(className);
			  

Available in IE8+, FF3.6+, Chrome 17+, Safari 5+:


document.querySelector(cssQuery);
document.querySelectorAll(cssQuery);
			  

getElement vs. getElements

Any method that starts with "getElement" will return a single node.


document.getElementById('uniqueID'); //returns a single node
			  

Any method that starts with "getElements" will return a array of nodes. To modify a single node, you will need to use bracket notation to select the correct one.


document.getElementsByTagName('p'); //returns multiple nodes
var specficParagraph = document.getElementsByTagName('p')[2];
			  

DOM Nodes: Attributes

You can access and change attributes of DOM nodes using dot notation.

To change this element:


<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
			  

We could change the src attribute this way:


var imgKitten = document.getElementById('kittenPic');
var oldSrc = imgKitten.src;
imgKitten.src = 'http://placekitten.com/100/500';
			  

DOM Nodes: Getting and Setting Attributes

You can also use getAttribute/setAttribute:


<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
			  

We could change the src attribute this way:


var imgKitten = document.getElementById('kittenPic');
var oldSrc = imgKitten.getAttribute('src');
imgKitten.setAttribute('src', 'http://placekitten.com/100/500');
			  

DOM Nodes: Styles

You can change page css using style

To make this CSS:


body {
  color: red;
}
			  

Use this JavaScript:


var pageNode = document.getElementsByTagName('body')[0];
pageNode.style.color = 'red';
			  

DOM Nodes: More Styles

Change any CSS property with a "-" to camelCase, and be sure to include a unit on any number

To make this CSS:


body {
  background-color: pink;
  padding-top: 10px;
}
			  

Use this JavaScript:


var pageNode = document.getElementsByTagName('body')[0]
pageNode.style.backgroundColor = 'pink';
pageNode.style.paddingTop = '10px';
			  

Let's Develop It

Create a simple HTML page or use this sample code.

Isolate a node (an element on the page) and change an attribute or add a new style.

DOM innerHTML

Each DOM node has an innerHTML property with the HTML of all its children. You can use the property to view or change the HTML of a node.

For example, you can overwrite the entire body:


var pageNode = document.getElementsByTagName('body')[0];
pageNode.innerHTML = '<h1>Oh Noes!</h1> <p>I just changed the whole page!</p>'
			  

Or just add some new content to the end:


pageNode.innerHTML += '...just adding this bit at the end of the page.';
			  

DOM innerHTML continued

You can also target a particular element

To fill this HTML element:


<p id="warning"></p>
			  

We can select the node and modify it:


var warningParagraph = document.getElementById('warning');
warningParagraph.innerHTML = 'Danger Will Robinson!';
			  

Creating New Nodes

The document object also provides ways to create nodes from scratch:


document.createElement(tagName);
document.createTextNode(text);
document.appendChild();
			  

Creating New Nodes: Sample Code


var pageNode = document.getElementsByTagName('body')[0];

var newImg = document.createElement('img');
newImg.src = 'http://placekitten.com/400/300';
newImg.style.border = '1px solid black';
pageNode.appendChild(newImg);

var newParagraph = document.createElement('p');
var paragraphText = document.createTextNode('Squee!');
newParagraph.appendChild(paragraphText);
pageNode.appendChild(newParagraph);
			  

Let's Develop It

Create a new paragraph element and add it to a div on your page.

Resources