Manipulating documents

When writing web pages and apps, one of the most common things you'll want to do is manipulate the document structure in some way. This is usually done by using the Document Object Model (DOM), a set of APIs for controlling HTML and styling information that makes heavy use of the Document object. In this article we'll look at how to use the DOM in detail, along with some other interesting APIs that can alter your environment in interesting ways.

Prerequisites: A basic understanding of HTML, CSS, and JavaScript — including JavaScript objects.
Objective: To gain familiarity with the core DOM APIs, and the other APIs commonly associated with DOM and document manipulation.

The important parts of a web browser

Web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using JavaScript. You might think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security. Imagine if a website could get access to your stored passwords or other sensitive information, and log into websites as if it were you?

Despite the limitations, Web APIs still give us access to a lot of functionality that enable us to do a great many things with web pages. There are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages:

Important parts of web browser; the document is the web page. The window includes the entire document and also the tab. The navigator is the browser, which includes the window (which includes the document) and all other windows.

In this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides.

The document object model

The document currently loaded in each one of your browser tabs is represented by a document object model. This is a "tree structure" representation created by the browser that enables the HTML structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the DOM with JavaScript after the page has been rendered.

We have created a simple example page at dom-example.html (see it live also). Try opening this up in your browser — it is a very simple page containing a element inside which you can find an image, and a paragraph with a link inside. The HTML source code looks like this:

doctype html> html lang="en-US"> head> meta charset="utf-8" /> title>Simple DOM exampletitle> head> body> section> img src="dinosaur.png" alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth." /> p> Here we will add a link to the a href="https://www.mozilla.org/">Mozilla homepagea> p> section> body> html> 

The DOM on the other hand looks like this:

Tree structure representation of Document Object Model: The top node is the doctype and HTML element. Child nodes of the HTML include head and body. Each child element is a branch. All text, even white space, is shown as well.

Note: This DOM tree diagram was created using Ian Hickson's Live DOM viewer.

Each entry in the tree is called a node. You can see in the diagram above that some nodes represent elements (identified as HTML , HEAD , META and so on) and others represent text (identified as #text ). There are other types of nodes as well, but these are the main ones you'll encounter.

Nodes are also referred to by their position in the tree relative to other nodes:

It is useful to familiarize yourself with this terminology before working with the DOM, as a number of the code terms you'll come across make use of them. You may have also come across them if you have studied CSS (e.g. descendant selector, child selector).

Active learning: Basic DOM manipulation

To start learning about DOM manipulation, let's begin with a practical example.

  1. Take a local copy of the dom-example.html page and the image that goes along with it.
  2. Add a element just above the closing tag.
  3. To manipulate an element inside the DOM, you first need to select it and store a reference to it inside a variable. Inside your script element, add the following line:

const link = document.querySelector("a"); 
.textContent = "Mozilla Developer Network"; 
.href = "https://developer.mozilla.org"; 

Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. Document.querySelector() is the recommended modern approach. It is convenient because it allows you to select elements using CSS selectors. The above querySelector() call will match the first element that appears in the document. If you wanted to match and do things to multiple elements, you could use Document.querySelectorAll() , which matches every element in the document that matches the selector, and stores references to them in an array-like object called a NodeList .

There are older methods available for grabbing element references, such as:

These two work better in older browsers than the modern methods like querySelector() , but are not as convenient. Have a look and see what others you can find!

Creating and placing new nodes

The above has given you a little taste of what you can do, but let's go further and look at how we can create new elements.

const sect = document.querySelector("section"); 
const para = document.createElement("p"); para.textContent = "We hope you enjoyed the ride."; 
.appendChild(para); 
const text = document.createTextNode( " — the premier source for web development knowledge.", ); 
const linkPara = document.querySelector("p"); linkPara.appendChild(text); 

That's most of what you need for adding nodes to the DOM — you'll make a lot of use of these methods when building dynamic interfaces (we'll look at some examples later).

Moving and removing elements

There may be times when you want to move nodes, or delete them from the DOM altogether. This is perfectly possible.

If we wanted to move the paragraph with the link inside it to the bottom of the section, we could do this:

.appendChild(linkPara); 

This moves the paragraph down to the bottom of the section. You might have thought it would make a second copy of it, but this is not the case — linkPara is a reference to the one and only copy of that paragraph. If you wanted to make a copy and add that as well, you'd need to use Node.cloneNode() instead.

Removing a node is pretty simple as well, at least when you have a reference to the node to be removed and its parent. In our current case, we just use Node.removeChild() , like this:

.removeChild(linkPara); 

When you want to remove a node based only on a reference to itself, which is fairly common, you can use Element.remove() :

.remove(); 

This method is not supported in older browsers. They have no method to tell a node to remove itself, so you'd have to do the following.

.parentNode.removeChild(linkPara); 

Have a go at adding the above lines to your code.

Manipulating styles

It is possible to manipulate CSS styles via JavaScript in a variety of ways.

To start with, you can get a list of all the stylesheets attached to a document using Document.stylesheets , which returns an array-like object with CSSStyleSheet objects. You can then add/remove styles as wished. However, we're not going to expand on those features because they are a somewhat archaic and difficult way to manipulate style. There are much easier ways.

The first way is to add inline styles directly onto elements you want to dynamically style. This is done with the HTMLElement.style property, which contains inline styling information for each element in the document. You can set properties of this object to directly update element styles.

    As an example, try adding these lines to our ongoing example:

.style.color = "white"; para.style.backgroundColor = "black"; para.style.padding = "10px"; para.style.width = "250px"; para.style.textAlign = "center"; 
p style="color: white; background-color: black; padding: 10px; width: 250px; text-align: center;"> We hope you enjoyed the ride. p> 

Note: Notice how the JavaScript property versions of the CSS styles are written in lower camel case whereas the CSS versions are hyphenated (kebab-case) (e.g. backgroundColor versus background-color ). Make sure you don't get these mixed up, otherwise it won't work.

There is another common way to dynamically manipulate styles on your document, which we'll look at now.

  1. Delete the previous five lines you added to the JavaScript.
  2. Add the following inside your HTML :

style> .highlight  color: white; background-color: black; padding: 10px; width: 250px; text-align: center; > style> 
.setAttribute("class", "highlight"); 

Which method you choose is up to you; both have their advantages and disadvantages. The first method takes less setup and is good for simple uses, whereas the second method is more purist (no mixing CSS and JavaScript, no inline styles, which are seen as a bad practice). As you start building larger and more involved apps, you will probably start using the second method more, but it is really up to you.

At this point, we haven't really done anything useful! There is no point using JavaScript to create static content — you might as well just write it into your HTML and not use JavaScript. It is more complex than HTML, and creating your content with JavaScript also has other issues attached to it (such as not being readable by search engines).

In the next section we will look at a more practical use of DOM APIs.

Active learning: A dynamic shopping list

In this challenge we want to make a simple shopping list example that allows you to dynamically add items to the list using a form input and button. When you add an item to the input and press the button:

The finished demo will look something like this:

Demo layout of a shopping list. A

To complete the exercise, follow the steps below, and make sure that the list behaves as described above.

  1. To start with, download a copy of our shopping-list.html starting file and make a copy of it somewhere. You'll see that it has some minimal CSS, a div with a label, input, and button, and an empty list and element. You'll be making all your additions inside the script.
  2. Create three variables that hold references to the list ( ), , and elements.
  3. Create a function that will run in response to the button being clicked.
  4. Inside the function body, start off by storing the current value of the input element in a variable.
  5. Next, empty the input element by setting its value to an empty string — '' .
  6. Create three new elements — a list item ( ), , and , and store them in variables.
  7. Append the span and the button as children of the list item.
  8. Set the text content of the span to the input element value you saved earlier, and the text content of the button to 'Delete'.
  9. Append the list item as a child of the list.
  10. Attach an event handler to the delete button so that, when clicked, it will delete the entire list item (
  11. . ).
  12. Finally, use the focus() method to focus the input element ready for entering the next shopping list item.

Note: If you get really stuck, have a look at our finished shopping list (see it running live also).

Summary

We have reached the end of our study of document and DOM manipulation. At this point you should understand what the important parts of a web browser are with respect to controlling documents and other aspects of the user's web experience. Most importantly, you should understand what the Document Object Model is, and how to manipulate it to create useful functionality.

See also

There are lots more features you can use to manipulate your documents. Check out some of our references and see what you can discover:

(See our Web API index for the full list of Web APIs documented on MDN!)