I briefly mentioned the Document Object Model (DOM) in my introduction section, its a programming interface for HTML and XML documents, the DOM is a heirarchical tree of nodes which allows a developer to add, remove and modify parts of a web page easily.
To recap the web page (HTML) can be represented as a tree node, if we look at the code on the left this can be represented as a tree node on the right, also know as the DOM, each node as a relationship with surrounding nodes in a paerent/child relationship which i will discuss I detail later.
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<p> Hello World!</p>
</body>
</html> |
![]() |
DOM level 1 describes an interface called a Node which can be a number of different node types, all node types inherit from Node in Javascript, so they have the same basic properties and methods, the twelve node types are below
You can test a nodes type using s simple piece of code
| Node type | if (someNode.nodeType == Node.ELEMENT_NODE){
console.log("Your type is" + someNode.nodeType);
} |
| nodeName | console.log(someNode.nodeName); // will be the elements tag name |
As I mentioned above Nodes have relationships with one and another, the Node could be a parent, child or a sibling or a combination, for example it could be parent and a child of another parent, the diagram below show the possible relationships a node can have.

To navigate around the nodes there are various methods
Javascript uses the document type to represent document nodes, the entire HTML document is represented by the document object, which is part of the Browser Object Model (BOM), the document object is a property of window and has global access, it can represents HTML or XML pages.
| Document type | <html>
<body>
....
</body>
</html>
Note:
let html = document.documentElement; // get reference to <html>
console.log(html === document.childNodes[0]); // true
console.log(html === document.firstChild); // true |
| doctype element | let doctype = document.doctype; // get reference to |
In the above code, there is one document child node, the <html> element you can access this element from the document.documentElement, document.childNodes list or the document.firstChild, if you have a first line of <!DOCTYPE html> then this won't be true.
You can access the body directly and other document elements
| body access | let body = document.body; // get reference to |
| title | let title = document.title; |
| URL, domain, referrer | let url = document.url; // http://www.datadisk.co.uk let domain = document.domain; // datadisk.co.uk let domain.referred; // http://www.datadisk.co.uk |
There are a number of ways to retrieve document elements
| method | element attribute or tag | command |
|---|---|---|
| getElementById | id | let div = document.getElementById("myDiv");
|
| getElementsByTagName | <img>, <anchors>, <applets>, <forms>, <links>, etc |
let images = document.getElementsByTagName("img"); |
| getElementsByName | name | let radios = document.getElementsByName("color"); |
The element type represents an XML or HTML element, there are a number of element types
| HTML elements | <div id="myDiv" class="bd" title="Body text" lang="en" dir="ltr">
let div = document.getElementById("myDiv");
console.log(div.id); // "myDiv"
console.log(div.className); // "bd"
console.log(div.title); // "Body text"
console.log(div.lang); // "en"
console.log(div.dir); // "ltr" |
| using getAttribute, setAttribute, removeAttribute | let div = document.getElementById("myDiv");
console.log(div.getAttribute("id")); // "myDiv"
console.log(div.getAttribute("class")); // "bd"
console.log(div.getAttribute("title")); // "Body text"
console.log(div.getAttribute("lang")); // "en"
console.log(div.getAttribute("dir")); // "ltr"
div.setAttribute("id", "someOtherId");
div.setAttribute("class", "ft");
div.setAttribute("title", "Some other text"); |
You can create elements, set attrinbutes and place it somewhere in the web page
| Create elements | let div = document.createElement("div");
div2.setAttribute("id", "Paul"); // set an Attribute
div2.innerHTML = "Paul valle"; // fill with some text
div.append(div2); // place it somehwere in the page
|
Text type is th text representation of an element, there are a number of methods to manipulate the test
| Create text node | let textNode = document.createTextNode("Hello World!"); |
| appendData | let textNode = document.createTextNode("Hello ");
textNode.appendData("World!")
div.appendChild(textNode); |
Comment type inherits from Text type, so you can use the same methods that text type uses,
| Create comment type | let comment = document.createComment("A comment"); |
Creating and Manipulating Tables
You can create and manipulate tables using a number of properties and methods associated with tables, i will list a few but there are many more
| Table creation and manipulating | // create the table
let table = document.createElement("table");
table.border = 1;
table.width = "100%";
// create the tbody
let tbody = document.createElement("tbody");
table.appendChild(tbody);
// create the first row
tbody.insertRow(0);
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode("Cell 1,1"));
tbody.rows[0].insertCell(1);
tbody.rows[0].cells[1].appendChild(document.createTextNode("Cell 2,1")); |
Mutation Observers is new to the DOM, and allows you to asynchronously execute a callback when the DOM is modified. You can observe the entire DOM tree, or a single element, element attributes, child nodes, text.
You start by creating a MutationObserver and pass it a callback function, then you use the observe() method to link the observer to the DOM.
| Create Observer | let observer = new MutationObserver(() => console.log('DOM was mutated!'));
observer.observe(document.body, { attributes: true });
document.body.className = 'change_dom';
console.log('Changed body class'); |
To terminate the observer you can use the discount() method
| Disconnect observer | let observer = new MutationObserver(() => console.log('DOM was mutated!'));
observer.observe(document.body, { attributes: true });
observer.disconnect(); |
You can reattach the observer
| Reattach the observer | observer.observe(document.body, { attributes: true }); |
You can observe subtree, attributes, attributeFilter, attributeOldValue, characterData, characterDataOldValue, childList
| Observe examples | observer.observe(document.body, { attributeFilter: ['foo'] });
observer.observe(document.body, { attributeOldValue: true });
observer.observe(document.body.firstChild, { characterData: true });
observer.observe(document.body, { childList: true });
observer.observe(document.body, { attributes: true, subtree: true });
|
There are two extensions that can be used called Selectors API and HTML5, which can be used to retrieve elements from the DOM.
The selectors API has two levels 1 and 2 which defined a of methods to query and find elements on a web page, the query contains of a CSS pattern which can be as simple or as complex as you like. Level 1 defines the querySelector() and the queryselectorAll() and Level 2 defines the matches(), find(), and finalAll() but only matches seems to be implemented at this time.
| querySelector example | // Get the body element
let body = document.querySelector("body");
// Get the element with the ID "myID"
let myDiv = document.querySelector("#myID");
// Get first element with a class of "myClass"
let selected = document.querySelector(".myClass");
// Get first image with class of "button"
let img = document.body.querySelector("img.button");
Note: will return the first element found or null if none are found |
| querySelectAll example | // Get all <em> elements in a <div> (similar to getElementsByTagName("em"))
let ems = document.getElementById("myDiv").querySelectorAll("em");
// Get all elements that have "myClass" as a class
let selecteds = document.querySelectorAll(".myClass");
// Get all <strong> elements inside of <p> elements
let strongs = document.querySelectorAll("p strong");
Note: all matching nodes are returned or null if none are found |
| matches example | let match = document.body.matches(".datadisk"); // will return true or false |
HTML5 was a major improvement over HTML4, a number of methods can be used to retrieve elements from the DOM
| getElementsByClassName example | // You can use one or more class names
let allCurrentUsernames = document.getElementsByClassName("blank datadisk");
console.log(allCurrentUsernames);
Note: only the elements in the subtree of the root from which it was called will be returned, it is idea to attach events too. |
| classList example | // Remove the "disabled" class
div.classList.remove("disabled");
// Add the "current" class
div.classList.add("current");
// Toggle the "user" class
div.classList.toggle("user");
Note used to add, remove, toggle classes in the class attribute. |
HTML5 has a number of properties and methods that you can use to change the HTML document, hasFocus(), contains(), readyState, compatMode, characterSet, the data- prefix and innerHTML and outerHTML.