DOM - javascript - Javascript DOM

Manipulating HTML Through the Javascript Document Object Model (DOM)

Javascript creates dynamic content on web pages by manipulating the underlying HTML structure. Browsers manage HTML internally as a tree of objects called the Document Object Model, or DOM. Developers refer to the tree objects as “elements.” The DOM also applies to XML and XHTML documents, which most modern browsers can display as well.

The DOM standard specifies how a browser builds an HTML tree and how scripting languages like Javascript should access elements in that tree. Although the Javascript standard implements concepts from the DOM standard, the two standards are different, maintained by different groups.

Components of the Javascript DOM

HTML elements read by a browser into the Javascript DOM are called “nodes.” Nodes are the core components of the Javascript DOM; they each have their own properties and they each are addressable and editable by Javascript.

The Javascript DOM defines each HTML element, the element’s properties, and any events that the element handles. For example, a button element, as part of its definition, contains a click event for when a user interacts with the button.

let myButton = document.createElement("button");
myButton.click(function() {
    console.log("click!");
});

The top node, the one that contains all other nodes in the Javascript DOM, is called the “root node.” To access any nodes within the Javascript DOM or any DOM properties, refer to the root node first. Javascript calls the root node document. The following examples use the document object to access the HTML body node and doctype.

document.body;    // The "body" node and all elements inside it
document.doctype; // The doctype for the element

All Javascript DOM nodes have properties that refer to nodes around them or to important information contained within that node. These properties are too numerous to list here; some commonly-used examples are:

element.parentNode;   // Parent of element
element.firstChild;   // First child of element
element.childNodes;   // All children of element
element.id;           // Unique ID of element

Depending on the Javascript DOM implementation, root and element properties may return null or undefined if they are not explicitly set to a value. Check for both values when determining if a property doesn’t exist, especially when making a Javascript program compatible with older browsers.

Accessing Nodes with the Javascript DOM

As mentioned earlier, accessing nodes inside the Javascript DOM requires you to start with the document, the root of the HTML tree. There are many methods that select nodes, either individually or in a group, from the Javascript DOM by starting with the document.

Methods that retrieve nodes from the document require a parameter called a “selector” that tells the method which nodes to get. Selectors can be element IDs, HTML tag names, HTML class names, displayed styles, or a combination of these, depending on the node retrieval method.

Retrieving a Node Using getElementById()

The method getElementById() retrieves a single node from the DOM by its ID. An ID must be unique within the DOM or this method will throw an error. Be careful not to capitalize the final letter of this method even though the abbreviation “ID” commonly capitalizes both letters — this is a common mistake that prevents Javascript from recognizing the method.

let myElement1 = document.getElementById("myId");  // Correct
let myElement2 = document.getElementByID("myId");  // WRONG!!!

Retrieving a Group of Nodes by Their HTML Tags Using getElementByTagName()

The method getElementsByTagName() retrieves a group of nodes from the DOM based on their element tags. Javascript returns these nodes as a structure called an HTMLCollection. To access nodes in this list, use a for loop, as in this example that accesses all hyperlink elements.

let linkElements = document.getElementByTagName("a");
for (let i = 0; i < linkElements.length; i++) {
    console.log(linkElements[i]);
}

Retrieving a Group of Nodes by a Single CSS Class Name Using getElementByClassName()

The method getElementsByClassName() works similarly to getElementsByTagName(), except that the selector must be the name of a CSS class. Never create a class name that is the same as an HTML tag name.

let infoElements = document.getElementByClassName("infos");
for (let i = 0; i < infoElements.length; i++) {
    console.log(infoElements[i]);
}

Retrieving a Group of Nodes by Many CSS Style Selectors using querySelectorAll()

The method querySelectorAll() is similar to the previous two methods, but its selector must be one or more CSS style selectors. Separate multiple selectors with a comma. Instead of an HTMLCollection, this method returns a NodeList, which is a static collection of nodes isolated from the document.

let styledElements = document.querySelectorAll("class1,purple");
for (let i = 0; i < styledElements.length; i++) {
    console.log(styledElements[i]);
}

Changing HTML with the Javascript DOM

Changing HTML with the Javascript DOM could also be considered a form of printing and output, since changes in HTML are the result of Javascript execution.

Direct HTML Manipulation with innerHTML()

The innerHTML() method changes the HTML within a specific DOM node. If you use this method on the document body, it rewrites the entire visible document.

// Fill an element with more HTML
document.getElementById("test").innerHTML("<span>more</span>");

// Rewrite the document body
document.body.innerHTML("<p>A paragraph.</p>);

Creating and Appending New HTML Nodes with createElement() and appendChild()

Adding HTML to the document with innerHTML() is prone to error when HTML strings become complicated. It is often clearer and simpler to create new nodes individually and add them to the Javascript DOM manually. Use the createElement() method to create a node and the appendChild() method to add that node to the Javascript DOM.

let body = document.body;
let elem = document.createElement("p");
elem.innerHTML("Paragraph text");
body.appendChild(elem);

Node Manipulation with removeChild() and replaceChild()

The Javascript DOM also allows removal and replacement of nodes. Use the removeChild() method to remove nodes and the replaceChild() method to replace nodes. Do not use either of these methods on the document body.

let elemA = document.getElementById("e1");
let elemB = document.getElementById("e2");
let elemC = document.getElementById("e3");

// Remove elemA
document.removeChild(elemA);

// Replace elemB with elemC
document.replaceChild(elemB, elemC);

The removeChild() and replaceChild() methods do not check for missing nodes because they assume that the nodes passed to them already exist in the DOM. Make sure this is true before using those methods.

Conclusion

Without the Javascript DOM, developers couldn’t create dynamic content in web pages. The HTML class and ID selectors identify nodes clearly so developers can target their dynamic content to precise places and times over a web page’s usage time.

Targeted changes to specific nodes in the Javascript DOM create dynamic content that doesn’t affect the rest of a web page. Users rely on the Javascript DOM for information like this on most modern web pages.

Enroll in our Intro to Programming Nanodegree Program today to learn more about the Javascript DOM and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni