Week 02, Day 03.

What we covered today:

The Document Object Model (DOM)

What is the DOM?

It's the HTML that you wrote, when it is parsed by the browser. After it is parsed - it is known as the DOM. It can be different to the HTML you wrote, if the browser fixes issues in your code, if javascript changes it etc.

How do we use it?

The document object gives us ways of accessing and changing the DOM of the current webpage.

General strategy:

  • Find the DOM node using an access method
  • Store it in a variable
  • Manipule the DOM node by changing its attributes, styles, inner HTML, or appending new nodes to it.

Here are some exercises to test this stuff.

Get Element by ID

// The method signature:
// document.getElementById(id);

// If the HTML had:
// <img id="mainpicture" src="http://placekitten.com/200/300">
// We'd access it this way:
var img = document.getElementById('mainpicture');

// DON'T USE THE HASH!

Get Elements by Tag Name

// The method signature:
// document.getElementsByTagName(tagName);

// If the HTML had:
<li class="catname">Lizzie</li>
<li class="catname">Daemon</li>
// We'd access it this way:
var listItems = document.getElementsByTagName('li');
for (var i =0; i < listItems.length; i++) {
  var listItem = listItems[i];
}

Query Selector and Query Selector All

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

Remember, some of these methods return arrays and some return single things!

Will return Single Elements

getElementById()
querySelector() * returns only the first of the matching elements
  var firstCatName = document.querySelector('ul li.catname');

Will return an Array

Others return a collection of elements in an array:

getElementByClassName()
getElementByTagName()
querySelectorAll()
  var catNames = document.querySelectorAll('ul li.catname');
  var firstCatName = catNames[0];

Do these exercises

Changing Attributes with Javascript

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

If we had this HTML:

<img id="mainpicture" src="http://placekitten.com/200/300">

We can change the src attribute this way:

var oldSrc = img.src;
img.src = 'http://placekitten.com/100/500';

// To set class, use the property className:
img.className = "picture";

Changing Styles with Javascript

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

If we had this CSS:

body {
  color: red;
}

We'd run this JS:

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

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

//To replicate this:

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

Changing an elements HTML

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

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

You can read out the HTML like this:

console.log(pageNode.innerHTML);

// You can set innerHTML yourself to change the contents of the node:
pageNode.innerHTML = "<h1>Oh Noes!</h1> <p>I just changed the whole page!</p>"

// You can also just add to the innerHTML instead of replace:
pageNode.innerHTML += "...just adding this bit at the end of the page.";

DOM Modifying

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

document.createElement(tagName);

document.createTextNode(text);

document.appendChild();

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

Have a crack at these exercises

Events

Adding Event Listeners

In IE 9+ (and all other browsers):

domNode.addEventListener(eventType, eventListener, useCapture);

// HTML = <button id="counter">0</button>

var counterButton = document.getElementById('counter');
var button = document.querySelector('button')
button.addEventListener('click', makeMadLib);

var onButtonClick = function() {
    counterButton.innerHTML = parseInt(counterButton.innerHTML) + 1;
};
counterButton.addEventListener('click', onButtonClick, false);

Some Event Types

The browser triggers many events. A short list:

  • mouse events (MouseEvent): mousedown, mouseup , click, dblclick, mousemove, mouseover, mousewheel , mouseout, contextmenu
  • touch events (TouchEvent): touchstart, touchmove, touchend, touchcancel
  • keyboard events (KeyboardEvent): keydown, keypress, keyup
  • form events: focus, blur, change, submit
  • window events: scroll, resize, hashchange, load, unload

Getting Details from a Form

// HTML
// <input id="myname" type="text">
// <button id="button">Say My Name</button>

var button = document.getElementById('button');
var onClick = function(event) {
    var myName = document.getElementById("myname").value;
    alert("Hi, " + myName);
};
button.addEventListener('click', onClick);

Have a crack at these exercises and here are some slides that may help.