Introduction to DOM Manipulation

Introduction to DOM Manipulation

ยท

12 min read

When building apps or websites one of the most powerful tools developers have at their disposal is the ability to manipulate the DOM (Document Object Model). This post explains the basics of DOM Manipulation.

What is the DOM?

The Document Object Model, or DOM for short, is a platform and language independent model for representing HTML or XML documents. It is basically an object-oriented representation of a web page. It represents the logical structure of a web page in such a way that a programming language like JavaScript can be used to change the document structure, style and content.

The DOM that represents an HTML document is referred to as the HTML DOM. Similarly, the DOM that represents an XML document is referred to as the XML DOM. Our focus in this tutorial is the HTML DOM which provides an interface for accessing and manipulating HTML documents with JavaScript.

Almost everything found in an HTML document can be accessed, updated, removed, or added using JavaScript code with the help of the DOM.

DOM Structure

Before we start looking at what DOM manipulation is all about, it is important that we first study the structure of the DOM. The HTML DOM has a hierarchical tree-like structure made up of DOM objects called nodes. The very first node at the head of the DOM is the document node. HTML elements (element nodes) are added to the DOM tree beneath the Document node. Like most things in computing, DOM nodes can have various types of relationships with other nodes. A DOM node could either be a parent of another node or nodes, child of a parent node or a sibling to other nodes. Now let's see how a DOM tree looks like and we are going to use the HTML code below for this;

<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1>Mobile OS</h1>
    <ul>
        <li>Android</li>
        <li>iOS</li>
    </ul>
</body>
</html>

This is DOM tree for the HTML code above;

html-dom-illustration.png

Now that we have looked at the DOM structure it is critical importance that we how we can find specific DOM node in order to be able to carryout various actions on them. We will look at how to select or find DOM elements by identifier. The identifiers include;

  • By ID.
  • Class
  • Tagname and
  • CSS query selector.

Selecting Elements by ID

To select a DOM element by its ID we use the document.getElementById( ) method. This method takes in a single string which is the ID of the element that is being selected.

Selecting Elements by Class Name

The document.getElementByClassName( ) method is used. It takes in a single string argument and return a live HTMLCollection of all the elements that match the given class name.

Selecting Elements by Tag Name

To select an element by its tag name we use the document.getElementByTagName( ) method. It takes as argument a single string representing the tag to search for.

Selecting Elements by CSS Query Selector.

This is done with two functions; querySelectorAll( ) and querySelector( ). They both take in single string argument that represents a CSS selector string. querySelectorAll will return a static nodeList of all the elements that match the query while querySelector returns a single element.

After looking at some of the ways in which we can select DOM nodes, let's get to DOM Manipulation proper.

DOM Manipulation

Manipulating the HTML DOM is done in three principal ways which are;

  • Adding elements to the DOM.
  • Removing elements from the DOM and
  • Updating elements in the DOM.

Creating and Adding New Elements to the DOM

To add an element to the DOM, we need to create the element and then go on to add it to the DOM. DOM nodes can be created using the following DOM methods.

document.createElement()
Node.cloneNode()
document.createTextNode()

createElement() is called on the document node. It creates a new element but does not add it to the DOM. It takes as argument a string which is the tag name of the element to be created.

cloneNode() is used to create a copy of the DOM node on which it is called. It takes a single Boolean argument deep. If deep is false, only the node cloneNode is called on will be copied but if deep is true the node cloneNode is called on together with its entire DOM tree will be copied.

N/B: When a node is cloned, the node together with all its attributes and values are copied. Event listeners that are added inline in HTML are copied as well. So when you clone a node, be sure to check and update its attributes and their values where necessary.

createTextNode is used to create text-only nodes. It is used place text in an HTML element. It takes in a single string argument and returns a text node.

To add new nodes to the DOM, the following methods are used;

Node.appendChild()
Node.insertBefore()

Node.appendChild() adds a node to the end of the child list of the node on which it is called on. It takes in a single argument which is the child node that is to be added to the node on which appendChild is called on.

If the node passed to Node.appendChild() already exist in the DOM tree, it is moved from its current position to a new position as a child of its specified parent node.

Node.insertBefore() inserts a node in the child list of the node on which it is called in front of a specified reference node. It takes in two arguments, new node and the reference node. If the value of the referenced node is null, the new node is added to the end of the child list.

Note that reference node is not an optional argument. It is either you pass in a node or the value null.

Removing elements from the DOM

To remove an element from the DOM tree, removeChild() is used. It removes the specified child from the parent node on which it is called. It takes in a single argument and returns the child that is removed.

Updating elements in the DOM.

DOM nodes an be updated in the following ways;

  • Replacing the node.
  • Changing the innerHTML.
  • Changing attributes
  • Changing the class and
  • Changing the style

    A DOM node can have any of its child nodes replaced with the replaceChild() method. It is replaces the specified child node of a node it is called on with a new specified node. It takes in two arguments; the new child node and the child node that is to be replaced.

innerHTML is used to get/set HTML markup. It takes a string value which is parsed as HTML.

You can also modify by changing or updating its attributes. This is done with the following methods;

getAttribute()
setAttribute()
removeAttribute()

getAttribute() takes in a single string argument which is the attribute whose value we want to get and returns the value of that attribute. If the given attribute does not exist, the value returned will either be null or " " (an empty string).

setAttribute() sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

removeAttribute() removes the attribute with the specified name from the element. It has no return value.

To change an element's class information, there two properties we can make use of - they are className and classList property. The className property can be used to get/set class values. The classList returns a live DOMTokenList collection of the class attributes of the element. It has the following six helper functions.

  • add() - Used to add classes to an element. It takes in any number of string arguments which represent the classes that are to be added. If any of the classes specified already exist, it is ignored.

  • remove() - Used to remove the specified class value. Values that do not exist are ignored. It takes in any number of string arguments.

  • item() - It takes as argument a number and returns the class value that is indexed by this number in the DOMTokenList.
  • toggle() - Toggles a class value a string and an optional Boolean value 'force'. If force is set to true the class is added and removed if force is false.
  • contains() - This method checks if the class value that is passed into it exist and returns a Boolean value to show whether the class value exist or not.
  • replace() - This method is used to replace an existing class with a new one. It takes in two string arguments which are the class value that is to be replace and the new value.

Using all of what we have looked at in this blog post can help you harness the power of creating dynamic web pages. Thank you for making it this far, you should be proud of yourself. I'll like to answer any questions or help clarify any doubt you have. Drop any question in the comment section.