JS Objects & DOM

Objects

Objects are a data type that let us store a collection of properties and methods.

var objectName = { 
  propertyName
: propertyValue,
  propertyName
: propertyValue,
 
...
};
var aboutMe = {
  hometown
: "Pasadena, CA",
  hair
: "brown"
};
var lizzieTheCat = {
  age
: 18,
  furColor
: "grey",
  likes
: ["catnip", "milk"],
  birthday
: {"month": 7, "day": 17, year: 1994}
};

Objects Access

Access properties using "dot notation":

var aboutMe = {
  hometown
: "Pasadena, CA",
  hair
: "brown"
};

var myHometown = aboutMe.hometown;

Or using "bracket notation" (like arrays):

var myHair = aboutMe["hair"];

Non-existent properties will return undefined:

var myGender = aboutMe["gender"];

Changing Objects

Use dot or bracket notation with the assignment operator to change objects.

Change existing properties:

var aboutMe = {
  hometown
: "Pasadena, CA",
  hair
: "brown"
};
aboutMe
.hair = "blue";

Or add new properties:

aboutMe.gender = "female";

You can also delete properties:

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.');
}

Objects as Arguments

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: 1994}
}

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

describeCat
(lizzieTheCat);

Object methods

Object properties can also be functions. Object functions are called "methods".

var lizzieTheCat = {
  age
: 18,
  furColor
: 'grey',
  meow
: function() {
    console
.log('meowww');
 
},
  eat
: function(food) {
    console
.log('Yum, I love ' + food);  
 
},
  sleep
: function(numMinutes) {
   
for (var i = 0; i < numMinutes; i++) {
      console
.log('z');
   
}
 
}
};

Call object methods using dot notation:

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

Built-in Objects

JS provides several built-in objects:

HTML Editors

Since HTML files are just text files, many programs can be used to create them. Some programs provide special assistance for handling HTML, like syntax-highlighting or autocompletion.

WindowsMacOnline
Free Notepad++ TextWrangler, Smultron Cloud9 IDE, JSBin
$$ E-Text Editor TextMate, Coda, Espresso

HTML & CSS: Review

<!doctype html>
<html>
 
<head>
 
<meta charset="utf-8">
 
<title>All About Cats</title>
 
<style type="text/css">
   h1
{
     color
: red;
   
}
 
#mainpicture {
    border
: 1px solid black;
 
}
 
.catname {
    font
-weight: bold;
 
}
 
</style>    
 
</head>
 
<body>
 
<h1>CATS!</h1>
 
<img id="mainpicture" src="http://placekitten.com/200/300">
 
<p>So cute!</p>
 
<ul>
   
<li class="catname">Lizzie</li>
   
<li class="catname">Daemon</li>
 
</ul>
 
</body>
</html>

JS in HTML

You can put JS inside a script tag (commonly at bottom of the page):

  ...
 
<script>
  console
.log('IM ON A WEBPAGE!');
 
</script>
 
</body>
</html>

You can also put JS in an external file and reference it:

  ...
 
<script src="app.js"></script>
 
</body>
</html>

The DOM Tree

For this page:

DOM Inspecting

  • Chrome: Right-click -> "Inspect Element"
  • Firefox: Right-click -> "Inspect Element" -> "HTML"
  • IE: Open Tools -> Developer Tools

Chrome:

DOM Access

On every webpage, the document object gives us ways of accessing and changing the DOM.

Every DOM "node" has properties that let us traverse the DOM like a tree: parentNode, childNodes, firstChild, prevSibling, nextSibling.

var bodyNode = document.body;
var htmlNode = document.body.parentNode;
for (var i = 0; i < document.body.childNodes.length; i++) {
 
var childNode = document.body.childNodes[i];
}

DOM Access: Easier

The document object also provides methods for finding DOM nodes without traversing:

document.getElementById(id);
<img id="mainpicture" src="http://placekitten.com/200/300">
var img = document.getElementById('mainpicture');

document.getElementsByTagName(tagName);
<li class="catname">Lizzie</li>
<li class="catname">Daemon</li>
var listItems = document.getElementsByTagName('li');
for (var i =0; i < listItems.length; i++) {
 
var listItem = listItems[i];
}

DOM Access: HTML5

The HTML5 spec includes a few even more convenient methods.

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

document.getElementsByClassName(className);
var catNames = document.getElementsByClassName('catname');
for (var i =0; i < catNames.length; i++) {
 
var catName = catNames[i];
}

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

document.querySelector(cssQuery);
document
.querySelectorAll(cssQuery);
var catNames = document.querySelectorAll('ul li.catname');

DOM Nodes: Attributes

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

<img id="mainpicture" src="http://placekitten.com/200/300">
var img = document.getElementById('mainpicture');
var oldSrc = img.src;
img
.src = 'http://placekitten.com/100/500';

Or getAttribute/setAttribute:

var oldSrc = img.getAttribute('src');
img
.setAttribute('src', 'http://placekitten.com/100/500');

To set class, use the property className:

img.className = "picture";

DOM Nodes: Styles

You can change styles on DOM nodes via the style property:

body {
  color
: red;
}
document.body.style.color = 'red';

CSS property names with a "-" must be camelCased and number properties must have a unit:

body {
  background
-color: pink;
  padding
-top: 10px;
}
document.body.style.backgroundColor = 'pink';
document
.body.style.paddingTop = '10px';

You can also set CSS properties through a special style attribute on every DOM node. logo.style.display = 'none' This immediately makes the logo disappear. Notes:Some property names must be adapted to become valid JavaScript identifiers, e.g. margin-top becomes marginTop and class becomes className. Number-like properties must be set using proper CSS syntax with their units, e.g. logo.style.marginTop='10px', not just a plain number.

DOM innerHTML

Each DOM node has an innerHTML property with the HTML of all its children:

document.body.innerHTML;

You can set innerHTML yourself to change the contents of the node:

document.body.innerHTML = "<h1>Oh Noes!</h1> <p>I just changed the whole page!</p>"

You can also just add to the innerHTML instead of replace:

document.body.innerHTML += "...just adding this bit at the end of the page.";

Every node in the DOM tree has an innerHTML attribute that contains all of its children serialized back into HTML format. var nav = header.nextSibling.nextSibling;var oldNavHTML = nav.innerHTML;var oldHeaderHTML = header.innerHTML; You can also set the innerHTML attribute to replace the contents of any node.

DOM Modifying

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

document.createElement(tagName);
document
.createTextNode(text);
document
.appendChild();
var newImg = document.createElement('img');
newImg
.src = 'http://placekitten.com/400/300';
newImg
.style.border = '1px solid black';
document
.body.appendChild(newImg);
var newParagraph = document.createElement('p');
var paragraphText = document.createTextNode('Squee!');
newParagraph
.appendChild(paragraphText);
document
.body.appendChild(newParagraph);