DOM Manipulation Copy

Introduction to DOM

One of the most unique and useful abilities of JavaScript is its ability to manipulate the web pages. It can manipulate both the HTML and CSS of any web page through the DOM. But what is the DOM, and how do we go about changing it? Let’s jump right in…

Learning Objectives

  • DOM in relation to a web page
  • The difference between a "node" and an "element"
  • How to target nodes with "selectors"
  • The basic methods for finding/adding/removing and altering DOM nodes
  • The difference between a "nodelist" and an "array of nodes"


Watch An Introduction to Browser Rendering.

Duration: 8 minutes

Read: What, exactly, is the DOM?

DOM – Document Object Model

The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage – a tree of "nodes" with different relationships depending on how they’re arranged in the HTML document.

<div id="wrapper">
  <div class="main"></div>
  <div class="secondary"></div>

In the above example, the <div class="main"></div> is a "child" of <div id="wrapper"></div> and a sibling to <div class="secondary"></div>. Think of it like a family tree. <div id="wrapper"></div> is a parent, with its children on the next level, each on their own "branch".

How to Target Nodes with Selectors

If we want to target a specific node that we want to work with then we use the selectors. These selectors can be a combination of CSS-style selectors and relationship properties.

We will start with the CSS-style selectors. If we want to target the <div class="main"></div> node then we could use the following selectors:

  • div.main
  • .main
  • #wrapper > .main
  • div#wrapper > div.main

In addition we can use relational selectors (i.e. firstElementChild or lastElementChild etc.) with special properties owned by the nodes.

const wrapper = document.querySelector('#wrapper');
// select the #wrapper div (don't worry about the syntax, we'll get there)
// select the first child of #wrapper => .main
const secondary = document.querySelector('.secondary');   
// select the .secondary div
// selects the prior sibling => .main

Basically in the examples above we identifying a certain node based on its relationship to the other nodes around it.

Introduction to DOM Methods

As stated before when the HTML code is parsed by a web browser it is converted to the DOM. Those nodes are objects that have many methods and properties attached to them. Therefore we use those methods and properties to manipulate our web page with JavaScript.

We will start with the query selectors and those selectors help us to target nodes.

Target an Element with Query Selectors

  • element.querySelector(selector) returns reference to the first match of selector
  • element.querySelectorAll(selectors) returns a "nodelist" containing references to all of the matches of the selectors

*There are several other, more specific queries, that offer potential (marginal) performance benefits, but we won’t be going over them now.

Important note: When using querySelectorAll, the return value is not an array. Although it might look an array it somewhat acts like an array, but it’s really a "nodelist". The big difference is that several array methods are missing from nodelists. One solution is to convert the nodelist into an array. You can do this with Array.from() or the spread operator.

Create Elements

  • document.createElement(tagName[, options]) creates a new element of tag type tagName. [options] in this case means you can add some optional parameters to the function.
const div = document.createElement('div');

Keep in mind that this function does NOT put your new element into the DOM – it simply creates it in memory. Thus before you place the element to the DOM you can add styles, classes, ids, text etc.

Then you can add that element to the DOM with the following methods.

Append Elements

  • parentNode.appendChild(childNode) appends childNode as the last child of parentNode
  • parentNode.insertBefore(newNode, referenceNode) inserts newNode into parentNode before referenceNode

Remove Elements

  • parentNode.removeChild(child) removes child from parentNode on the DOM and returns reference to child

Altering Elements

We can also alter the element’s own properties. In other words when we have a reference to an element we can use that reference and do many alterations to the element itself, such as add or remove an attribute, change classes, adding styles and much more.

Let’s see an example. First we will create a div element.

const div = document.createElement('div');                     
// create a new div referenced in the variable 'div'

In the following sections we will use that div to do several alterations to it.

Inline style

Now we will add the color purple and the background color gray in to our previously created div. = 'purple';                                      
// adds the indicated style rule = 'color: purple; background: gray';          
// adds several style rules
div.setAttribute('style', 'color: purple; background: gray');    
// adds several style rules

For further information on inline styles see the DOM Enlightenment’s section on CSS Style rules.

Please be aware that if you’re accessing a kebab-cased css rule from JS, you’ll either need to use camelcase or you’ll need to use bracket notation instead of dot notation.

For example: // doesn't work - attempts to subtract color from // accesses the divs background-color style['background-color'] // also works = "background-color: white" // ok in a string


Now let’s see how we can edit an attribute of an element.

div.setAttribute('id', 'myDiv');                              
// if id exists update it to 'myDiv' else create an id
// with value "myDiv"
// returns value of specified attribute, in this case
// "myDiv"
// removes specified attribute

For further information on available attributes see MDNs section on HTML Attributes.


Now we will see some examples of methods we use with the class that our element might has.

// adds class "content" to our new div
// remove "content" class from div
// if div doesn't have class "active" then add it, or if
// it does, then remove it

It is often standard (and more clean) to toggle a CSS style rather than adding and removing inline CSS.

Text content

Now we will see how we add text content to our element.

div.textContent = 'My first content!'                               
// creates a text node containing "Hello World!" and
// inserts it in div

HTML content

Now we will see how we add HTML content to our element.

div.innerHTML = '<span>My first content!</span>';                   
// renders the html inside div

*Note that textContent is preferable for adding text, and innerHTML should be used sparingly as it can create security risks if misused. For further information about this topic you can check this article.

Now let’s see an example as a review of what we have covered so far. So in the example we will create a DOM element and we will append it to a webpage.

<!-- HTML FILE -->
  <div id="wrapper"></div>
const wrapper = document.querySelector('#wrapper');
const container = document.createElement('div');
container.textContent = 'This is our text-content!';

First we get a reference to the wrapper div that already exists in our HTML. Then we create a new div and store it in the variable container. We add a class and some text to the container div and finally append that div to wrapper.

So, after the JavaScript code is run, our DOM tree will look like this:

<!-- DOM -->
  <div id="wrapper">
  	<div class="content">
      This is our text-content!

Something to keep in mind is that the Javascript doesn’t alter our HTML. The HTML file will look the same but the JavaScript changes what the browser renders.

Important note: JavaScript, for the most part, is run whenever the JS file is run, or when the script tag is encountered in the HTML. Therefore, If you include your JavaScript at the top of your file, many of these DOM manipulation methods will not work. This is due to the fact that the JS code is being run before the nodes are created in the DOM. So, the simplest way to fix this is to include your JavaScript at the bottom of your HTML file. In that way the Javascript runs after the DOM nodes are parsed and created.

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.