Week 02, Day 03
What we covered today:
- JavaScript - The Document Object Model (DOM)
- Accessing Elements
- Manipulating Elements
- Creating Elements
- Events
Warmup
Slides
JavaScript - The Document Object Model (DOM)
What is the DOM?
The Document Object Model, or 'DOM':
- Is a structural representation of HTML documents - the document is represented as a tree with nodes; and
- Defines methods for accessing, manipulating and creating those nodes.
JavaScript can't access or manipulate what's in the browser directly - that's just a bunch of pixels. JavaScript can, however, interact with the DOM.
The DOM is HTML after it has been parsed by the browser. 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 that DOM node in a variable
- Manipulate the DOM node by changing its attributes, styles, inner HTML, or appending new nodes to it.
Accessing elements
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!
Methods that return single elements
getElementById();
querySelector(); // returns only the first of the matching elements
var firstCatName = document.querySelector('ul li.catname');
Methods that will return an array of elements
Others return a collection of elements in an array:
getElementByClassName();
getElementByTagName();
querySelectorAll();
var catNames = document.querySelectorAll('ul li.catname');
var firstCatName = catNames[0];
Manipulating elements
Changing an element's attributes
You can access and change attributes of DOM nodes using JavaScript object dot notation.
If we had this HTML:
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 an element's style
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';
IMPORTANT: CSS property names with a "-" must be camelCased and number properties must have a unit:
For example, to replicate this CSS:
body {
background-color: pink;
padding-top: 10px;
font-style: oblique;
}
We would need to do this:
var pageNode = document.querySelector('body');
pageNode.style.backgroundColor = 'pink';
pageNode.style.paddingTop = '10px';
padgeNode.style.fontStyle = 'oblique';
Changing an element's 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.";
JavaScript - Document Object Model - Manipulating elements - Exercises
Creating elements
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);
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);
JavaScript - Document Object Model - Events - Further Reading
- MDN - JavaScript Events Reference
- MDN - Event Developer Guide
- CSS Tricks - JavaScript Key Codes
- keycode.info
Document Object Model - Events - Exercises
JavaScript - The Window Object
When you run JS in the browser, it gives you the window object with many useful properties and methods:
window.location.href; // Will return the URL
window.navigator.userAgent; // Tell you about the browser
window.scrollTo(10, 50);
Lots of things that we have been using are actually a part of the window object. As the window object is the assumed global object on a page.
window.alert("Hello world!"); // Same things
alert("Hello World!");
window.console.log("Hi"); // Same things
console.log("Hi");
Homework
- More DOM manipulation
- Catwalk
- If the link to the .gif in that Gist is broken, try this.
- Previous WDi Catwalks