JavaScript & the DOM
(Document-Object Model)

Review: HTML & CSS

JS Bin on jsbin.com

To open this JS Bin in a new window, click here.

Text Editors

Many text editors provide special assistance for writing HTML and CSS, like syntax-highlighting and autocompletion.

  • Sublime Text, Atom (Mac, Windows, Linux)
  • TextMate (Mac only)
  • Notepad++ (Windows only)
  • JSBin, JSFiddle, Codepen, Cloud9 (Online)
<h1>My JavaScript questions</h1>
<ul>
  <li>How do HTML/CSS and Javascript work together?</li>
  <li>How can I animate elements on the screen?</li>
</ul>

Including JavaScript in your HTML

You can write your JS inside a script tag in your HTML file:

<html>
  <body>
    <script>
      console.log("I am Javascript running on a web page!");
    </script>
  </body>
</html>

Including JavaScript in your HTML

You can also write your JS in a separate file and reference it from your HTML file via a script tag:

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

What is the DOM?

  • Document Object Model - i.e. a map of our HTML document
  • Defines the logical structure of an HTML document and how it is accessed and manipulated
  • Anything found in an HTML or XML document can be accessed, changed, deleted, or added by a programmer using the DOM

Inspecting the DOM

  • Google Chrome or Mozilla Firefox
    • Right-click on a web page and select "Inspect Element"
    • Shortcuts: Cmd-Opt-I (Mac), Ctrl-Shift-I (Windows)
  • Internet Explorer
    • Open Tools > "Developer Tools"
  • Safari
    • Unlock the Develop Menu by opening Safari > Preferences > Advanced, and checking the box, "Show Develop menu in menu bar."
    • Access by same methods as Chrome (above)

Accessing the DOM


The document object is globally available in your browser.

It allows you to access and manipulate the DOM of the current web page:

  1. Find the DOM node you want to change using an access method
  2. Store this DOM node as a variable
  3. Manipulate the DOM node
    • Change its attributes
    • Modify its styles
    • Give it new inner HTML
    • Append new nodes to it

DOM Access Methods


Finding DOM nodes by id:

document.getElementById(id);

Finding DOM nodes by tag name:

document.getElementsByTagName(tagName);

Finding DOM nodes by class name:

document.getElementsByClassName(className);

Finding DOM nodes by query selector:

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

Selecting Nodes From the DOM

HTML:

<ul id="hobby-list">
  <li class="hobby">Playing the banjo</li>
  <li class="hobby">Paddleboarding</li>
</ul>

JavaScript:

// By Id
var hobbiesList = document.getElementById('hobby-list');

// By Tag Name
var hobbies = document.getElementsByTagName('li');

// By Class Name
var alsoHobbies = document.getElementsByClassName('hobby');

// By CSS Query
var firstHobby = document.querySelector('ul li.hobby');
var againAlsoHobbies = document.querySelectorAll('ul li.hobby');

Returning Element vs. Array of Elements


getElementById() and querySelector()return a single element:

var hobbiesList = document.getElementById('hobby-list');
var firstHobby = document.querySelector('ul li.hobby');

getElementsByClassName(), getElementsByTagName(), and querySelectorAll() return a collection of elements (which acts like an array):

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

The DOM Detective Exercise

Manipulating a DOM Node's Attributes

You can access and change the attributes of a DOM node using dot notation.

<img id="lizzie-the-cat" src="http://placekitten.com/200/300">

Changing the src of an image:

var catImage = document.getElementById('lizzie');
var oldImageSource = catImage.src;
catImage.src = 'http://placekitten.com/300/200';

Changing the className of a DOM node:

var catImage = document.getElementById('lizzie');
catImage.className = "portrait";

Manipulating a DOM Node's Styles

You can access and change the styles of a DOM nodes via the style property. CSS property names with a "-" must be camelCased and number properties must have a unit.

CSS:

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

Applying the Same Styles via JavaScript:

var pageNode = document.body;
pageNode.style.color = 'red';
pageNode.style.backgroundColor = 'pink';
pageNode.style.paddingTop = '10px';

Manipulating a DOM Node's Inner HTML

Each DOM node has an innerHTML attribute that contains the HTML of all its children:

var pageNode = document.body;
console.log(pageNode.innerHTML);

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

pageNode.innerHTML = "<h1>Oh, no! Everything is gone!</h1>"

You can also just add to the innerHTML, instead of replacing it altogether:

pageNode.innerHTML += "P.S. Please do write back.";

innerHTML vs. textContent

If you're only changing the actual text of a node, textContent may be a better choice.

  • innerHTML
    • Works in older browsers
    • More powerful: can change code
    • Less secure: allows cross-site scripting (XSS)
  • textContent
    • Doesn't work in IE8 and below
    • Faster: the browser doesn't have to parse HTML
    • More secure: won't execute code

The Logo Hijack

Creating DOM Nodes

The document object also allows us to create new nodes from scratch:

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

Master of (DOM) Manipulation Exercise

Questions?

Return to Table of Contents