Dr. Greg Bernstein
Updated February 12th, 2021
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.
Introduction to the DOM. Fundamental.
DOM Enlightenment. A very complete free e-book.
The Basics of DOM Manipulation in Vanilla JavaScript. Just a portion of this for now.
Some of the APIs provided by most browsers
The DOM and related
Networking: Fetch and Websockets
Data Storage: Web Storage for small amounts of data, IndexedDB good for large amounts of data, poorly documented, but works well.
And many more…
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.
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.
window
and document
objects as starting pointsSome of the properties and methods:
Node.childNodes
, Node.firstChild
, Node.lastChild
Node.nodeName
(tag for HTMLElement), Node.nodeType
Node.appendChild()
, Node.insertBefore()
,Node.removeChild()
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!
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.
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>
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."
}
];
The document
represents the web page. Through the document
its elements we can query, enhance, and modify the webpage.
document.title
document.head
<head>
element of the current document.document.body
Returns the <body>
element of the current document.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])
document.getElementsByClassName()
, .getElementsByTagName()
, .getElementById(String id)
document.querySelector(String selector)
document.querySelectorAll(String selector)
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");
document.createElement()
document.createAttribute()
document.createDocumentFragment()
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`);
}
};
Add “all language information” function. No loops!
function addAll() {
myLanguages.forEach(function(lang){
addLangName(lang.name);
});
}
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.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.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.selectedStyleSheetSet
document.styleSheets
document.styleSheetSets
Almost everything in the document!
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
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>";
Try calling mystery()
on console of DOM Practice page
Element.classList
is a DOMTokenList containing the list of class attributes.
.contains()
, .add()
, .remove()
, .replace()
, .toggle()
and more.classList
Example Imystery()
solved…
function mystery() {
langSection.classList.toggle("myHide");
}
classList
Example IIJust 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;
}
Just like on Document
!
Element.getElementsByClassName()
, .getElementsByTagName()
, .getElementById(String id)
Element.querySelector(String selector)
Element.querySelectorAll(String selector)
Element.getAttribute()
, Element.setAttribute()
Element.hasAttribute()
, Element.removeAttribute()`Element.id
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)
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.
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.clientHeight
: Returns a Number representing the inner height of the element.
Element.clientWidth
: Returns a Number representing the inner width of the element.
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.
Window is the “default context” hence you can get all properties and methods by typing their name at the console
Window.innerHeight
, .innerWidth
, .outerHeight
, .outerWidth
Window.resizeBy()
, .resizeTo()
Window.screenX
, .screenY
Window.moveBy()
, .moveTo()
Window.find()
Window.getSelection()
Window.localStorage
Window.sessionStorage
Window.scrollMaxX
, .scrollMaxY
, .scrollX
, .scrollY
Window.scroll()
, .scrollBy()
, .scrollByLines()
, .scrollByPages()
, .scrollTo()