JavaScript DOM Introduction

Dr. Greg Bernstein

Updated February 12th, 2021

Intro to the JavaScript DOM

Learning Objectives

  • Understand the DOM in terms of a tree data structure for containment, and an inheritance hierarchy for functionality.

  • Understand and use the fundamental DOM interfaces: node, document, element and window

  • Be able to select and modify elements via the DOM APIs

  • Be able to create, insert/add, and remove elements via the DOM

  • Be able to alter the class attributes associated with an element via the classList API.

Readings

  1. Introduction to the DOM. Fundamental.

  2. DOM Enlightenment. A very complete free e-book.

  3. The Basics of DOM Manipulation in Vanilla JavaScript. Just a portion of this for now.

References

Web APIs

Some of the APIs provided by most browsers

What is the DOM?

From MDN:

The Document Object Model (DOM) is a programming interface for HTML documents. It provides a structured representation of the document and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content.

What is the DOM?

From MDN:

The DOM provides a representation of the document as a structured group of nodes and objects that have properties and methods. Essentially, it connects web pages to scripts or programming languages.

Accessing the DOM

  • The DOM is available to JavaScript running in a browser
  • We will use the window and document objects as starting points
  • For non-browser applications there are a variety of libraries to help work with HTML but these don’t need to implement the full DOM. For example the BeautifulSoup library for Python.

Containment Hierarchy

Inheritance Hierarchy

Document and Element inherit from Node

What’s in Node?

Some of the properties and methods:

  • Node.childNodes, Node.firstChild, Node.lastChild
  • Node.nodeName (tag for HTMLElement), Node.nodeType
  • Node.appendChild(), Node.insertBefore(),Node.removeChild()

Why Node?

The Node class provides functionality for creating, traversing, and modifying the DOM tree.

The elements that make up a document are modeled as a containment tree!

Parents and Children in a Containment Tree

  • An element gets one parent, the element that directly contains it, i.e., the element that directly contains the element nested within it!

  • An element can have zero or more children these are the elements that are directly nested within it.

Example Page

Open this in a new tab for practice: DOMExamples.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>DOM Practice HTML</title>
    <style>/* See file */  </style>
</head>
<body>
    <header>
        <h1 id="MyH1">Change This Great Document!</h1>
        <h2>Be Stylish, Be Cool, Be a Web Developer</h2>
        <p>Use the DOM!</p>
    </header>
    <section id="ProgLangs" class="myShow">
        <h2>Programming Languages I have Known</h2>
    </section>
    <footer>
        <p>Yes there have been other languages that I worked or dabbled with including: Matlab, Perl, Ruby, Assembly but none made as big as an impression as those mentioned above.</p>
        <p class="Close">Sincerely, <br> the <span class="Author">Occasional Programmer</span></p>
    </footer>

    <script>
      // To be shown next
    </script>
</body>
</html>

Example Page II

Data Portion of Script

// Set up some data for later
myLanguages = [{
        name: "Fortran",
        description: "I first met Fortran when I started my career at a Junior College. We used punch cards. The computer had 4k bytes of core memory. Hard to imagine. Hard to program."
    },
    {
        name: "Pascal",
        description: "My second programming when I was at Berkeley was Pascal. It seemed like a pleasant language. We have a very good tutorial book and a completely unreadable book on language details."
    },
    {
        name: "C",
        description: "In graduate school <em>C</em> was the new <em>cool</em> language. I used it for most of my research which involved a lot of computation."
    },
    {
        name: "C++",
        description: "After finishing school the object-oriented craze kicked in and <em>C++</em> was all the rage. Unfortunately it is also rather large and complicated with somewhat uneven cross-platform support. As the director of a large software project my team used C++ but not all of it."
    },
    {
        name: "Java",
        description: "Java was on the way in while I was in charge of that large project and we used it for systems that didn't have real-time constraints. Programmers tended to not make as many mistakes with Java. I used Java on my own and for consulting."
    },
    {
        name: "Python",
        description: "I can't remember when I first heard about python. But when sitting in on some astronomy graduate classes at Berkeley in the 2000s there was a push away from proprietary languages such as Matlab for scientific computing, with the desire for ease of use and rapid prototyping. Because it played well with other languages, Python could wrap good (but not easy to use) numerical code from Fortran, C, and C++. Despite the weird indentation thing I was quickly sold and moved most of my network research and teaching to Python."
    },
    {
        name: "JavaScript",
        description: "A toy for web kiddies was my first impression. However, I was interested in <em>true</em> cross platform graphical user interfaces. I had done some GUI programming on Windows, and with Java but neither seemed truly cross platform or easy to integrate with the numerical work (Java doesn't play very nice with other languages). With ES6 (aka ES2015) adopting a lot of nice practices I started using JavaScript, HTML, CSS plus a whole lot of open source 3rd party libraries to build my web GUIs and applications."
    }
];

Document

Page = Document

The document represents the web page. Through the document its elements we can query, enhance, and modify the webpage.

Basic Content

  • document.title
    • Sets or gets title of the current document.
  • document.head
    • Returns the <head> element of the current document.
  • document.body Returns the <body> element of the current document.

Examples

Try some Node functions on the DOM practice page

mybody = document.body;
// childNode includes text nodes
console.log(mybody.childNodes);
// try removing the <header> node
// I used something like
// mybody.removeChild(mybody.childNodes[1])

Element Queries

  • document.getElementsByClassName(), .getElementsByTagName(), .getElementById(String id)

  • document.querySelector(String selector)

    • Returns the first Element node within the document, in document order, that matches the specified CSS selectors.

Element Queries

  • document.querySelectorAll(String selector)
    • Returns a list of all the Element nodes within the document that match the specified CSS selectors.

Example: Selection

Selecting some elements on the page, putting them in global vars, try from command line.

// Get some elements on the page
langSection = document.getElementById("ProgLangs");
firstH1 = document.getElementById("MyH1");
author = document.querySelector("span.Author");  

Element Creation

  • document.createElement()
    • Creates a new element with the given tag name. We will use this directly
  • document.createAttribute()
    • Creates a new Attr object and returns it.
  • document.createDocumentFragment()
    • Creates a new document fragment. Can be used for more efficient creation.

Element Creation Example I

Run functions on DOM Practice page by calling them from console.

// Create paragraph string from data object
function createLangPara(langObj) {
  let lp = `<p class="Lang"><span class="LName">${langObj.name}</span> ${langObj.description}</p>`;
  return lp;
};

// Adds language info to document
function addLangName(lname) {
  // Lookup language info by name
  let langInfo = myLanguages.find(function(info) {
      return info.name === lname;
  });
  if (langInfo) {
      langP = createLangPara(langInfo);
      newP = document.createElement("p"); //Document
      langSection.appendChild(newP); //Node
      // Can't change outHTML unless element has a parent
      newP.outerHTML = langP; //Element
  } else {
      alert(`Language: ${lname} was not found`);
  }
};

Element Creation Example II

Add “all language information” function. No loops!

function addAll() {
  myLanguages.forEach(function(lang){
    addLangName(lang.name);
  });
}

Element Removal Example

Remove all <p>s from the <section>

function clearAll() {
    myPs = langSection.querySelectorAll("p");
    // Using Node interface
    myPs.forEach(function(p) {
        langSection.removeChild(p);
    });
    // Or Using Element interface and arrow function
    // myPs.forEach(p => p.remove());
}

Document Content Lists

document.forms - a list of the <form> elements within the current document.

document.images - a list of the images in the current document.

document.links - a list of all the hyperlinks in the document.

document.scripts - Returns all the <script> elements on the document.

Document Meta Information

  • document.charset, .doctype, .lastModified
  • document.URL, .documentURI, .location
  • document.cookie (list of the cookies for that document or sets a single cookie)
  • document.referrer (*the URI of the page that linked to this page)

Document Stylesheet Info

  • document.selectedStyleSheetSet
    • Returns which style sheet set is currently in use.
  • document.styleSheets
    • Returns a list of the style sheet objects on the current document.
  • document.styleSheetSets
    • Returns a list of the style sheet sets available on the document.

Elements

What are they?

Almost everything in the document!

Element Content

  • Element.innerHTML: a DOMString representing the markup of the element’s content. You can set!

  • Element.outerHTML: a DOMString representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string. Must have a parent to work

Example: Change Content

Using the already defined element variables copy, paste, modify the following in the console on the “DOM Practice” page.

currTime = new Date(); //Gets the current date/time
firstH1.innerHTML = `Good Morning, its ${currTime}`;
author.innerHTML = "<strong>The Current CS___ Lecturer</strong>";  

Element Classes

Try calling mystery() on console of DOM Practice page

  • Element.classList is a DOMTokenList containing the list of class attributes.

    • This is Powerfull! DOMTokenList supports: .contains(), .add(), .remove(), .replace(), .toggle() and more.
    • Gives you lots of control over classes associated with an element. You will use these a lot or the framework you use will.

classList Example I

mystery() solved…

function mystery() {
    langSection.classList.toggle("myHide");
}

classList Example II

Just two CSS classes and transition properties

.myShow {
    max-height: 300px;
    overflow-y: auto;
    margin-left: 1em;
    transition-property: margin-left;
    transition-delay: 0.5s;
    transition-duration: 2s;
}

.myHide {
    margin-left: -200em;
}

Element Queries

Just like on Document!

  • Element.getElementsByClassName(), .getElementsByTagName(), .getElementById(String id)

  • Element.querySelector(String selector)

  • Element.querySelectorAll(String selector)

Element Attributes

  • Element.getAttribute(), Element.setAttribute()
  • Element.hasAttribute(), Element.removeAttribute()`
  • Element.id

Element Scrolling

  • Properties: Element.scrollHeight, Element.scrollLeft, Element.scrollLeftMax, Element.scrollTop, Element.scrollTopMax, Element.scrollWidth

  • Methods: element.scroll(x-coord, y-coord), element.scrollBy(x-coord, y-coord), element.scrollIntoView() (scrolls parent)

Example: Scroll into View I

Write a function given a language name that will scroll that entry (if it exists) into view

  • Get all the <p>s in the language <section>

  • This is a NodeList, convert to array with Array.from(nodeListThingy)

  • Use the Array.find method with suitable finder function (Hint get the span.LName and check its innerHTML) to get the right <p> element

  • Call the <p>s scrollIntoView() method.

Example: Scroll into View II

My solution in “DOM Practice” page

function scroll2Lang(lang) {
    let myPs = langSection.querySelectorAll("p.Lang");
    let myPArray = Array.from(myPs);
    // Seach for the paragraph with the correct language name span
    let theP = myPArray.find(function(p) {
        return p.querySelector("span.LName").innerHTML === lang;
    });
    if (theP) { // does it exist?
        theP.scrollIntoView();
    }
}

Element Sizing Info

Element.clientHeight: Returns a Number representing the inner height of the element.

Element.clientWidth: Returns a Number representing the inner width of the element.

Window

The Window Object

From MDN:

The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the document.defaultView property.

Sizing and Placing the Window

Window is the “default context” hence you can get all properties and methods by typing their name at the console

  • Size
    • Window.innerHeight, .innerWidth, .outerHeight, .outerWidth
    • Window.resizeBy(), .resizeTo()
  • Placement
    • Window.screenX, .screenY
    • Window.moveBy(), .moveTo()

Window: URL & History

  • Window.history
    • Returns a reference to the history object.
  • Window.location Gets/sets the location, or current URL, of the window object.

Window: Search & Selection

  • Window.find()
    • Searches for a given string in a window.
  • Window.getSelection()
    • Returns the selection object representing the selected item(s).

Window: Storage

  • Window.localStorage
    • Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
  • Window.sessionStorage
    • Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it. Unavailable after page is closed.

Window: Scrolling

  • Scroll boundaries and position
    • Window.scrollMaxX, .scrollMaxY, .scrollX, .scrollY
  • Scroll control
    • Window.scroll(), .scrollBy(), .scrollByLines(), .scrollByPages(), .scrollTo()
// reveal.js plugins