Javascript DOM Manipulation

Javascript DOM Manipulation

In this write-up, we'll learn how to:

Select elements using JavaScript
Alter properties of the elements
Create new elements and add them to the DOM

The DOM

The DOM (Document Object Model) is a object that represents the HTML and CSS of a web page. The DOM allows us to use JavaScript to interface with what the user sees.

You can think of the DOM as a tree. Think of how we usually nest HTML elements.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta/>
    <meta/>
</head>
<body>
    <h1></h1>
    <p>
        <a></a>
    </p>
    <ul>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</body>
</html>

The following is a visual of how your browser organizes this HTML in the DOM

dom_tree

It's a tree! And we'll use terminology that we would when talking about a family tree, like "parent", "child", "ancestor", and "sibling".

How can we interact with this tree you ask? In any way we please! We can remove children, add children, and change properties of elements like their content and styling.

Select

There are a few ways to select elements from the DOM.

document.getElementById()
document.getElementsByClassName()
document.querySelector()

Given this HTML:

<div id="greeting">Hello!</div>

We can select is by it's id. .getElementById returns the element as an object. In this example, we will assign that element to the variable myGreeting.

const myGreeting = document.getElementById("greeting")

document.getElementById("greeting") will return null if no elements have id="greeting".

Now that we have that element selected, we can alter anything property we want to about it! That's the fun stuff, so feel free to skip to that section.

In the meantime, there are some other useful methods.

By Class Name

const greetingArr = document.getElementsByClassName("greeting")

Notice the "s" on elements in getElementsByClassName. Any DOM method with the plural elements will return an array. You are able to loop over each element, or select an individual element with bracket notation.

greetingArr[0] would give us the first one.

By a CSS selector

You can do some more sophisticated selections with document.querySelector(). This method will return the first element it finds that matches the CSS selector given it. Here are a few examples:

`document.querySelector(".my-class")`
`document.querySelector("#my-id")`
`document.querySelector("p.black")`

document.querySelectorAll() is similar, but returns an array.

Here is the coolest use case I have run into with document.querySelectorAll()

const checkedBoxes = document.querySelectorAll("input[name=likes]:checked");

Here, we can select all input boxes with name="likes"

Alter

Let's use our HTML from above:

<div id="greeting">Hello!</div>

For practice, type out how you would select this div and assign that element to the variable myGreeting.

Now, console.dir(myGreeting)

Explore this object in the console. Try to figure out how to change it by changing it's different properties.

Screen-Shot-2019-08-29-at-9.34.01-AM

As you can see, we have access to the className, id, children, and content our element. We can reassign these attributes. Try to manipulate these properties on your own.

To you you started, our goal will be to change the background color of the greeting and the text.

Styling

If you'd like to try this on your own, it would be great practice. A good property to look at is the .style properties.

console.log(myGreeting.style)

The style object has properties for every CSS property. We can assign those properties to any value we'd like.

myGreeting.style.backgroundColor = "blue"

Text and Content

We can also manipulate the contents of elements.

const myGreeting = document.getElementById("greeting")
myGreeting.textContent = "Long time no see!"
myGreeting.textContent = "Long time no see!"

.textContent will replace any text.

See what happens if you run the following:

myGreeting.textContent = "<h1>Long time no see!</h1>"

If we'd like the text to be inside a HTML <h1>, we can use .innerHTML

myGreeting.innerHTML = "<h1>Long time no see!</h1>"

But that isn't the only or best way to add a new <h1> to the DOM. The DOM API also gives us a method to create new elements.

Create

In our most recent use of .innerHTML, we used a JavaScript string to wrap our text in an <h1>. We now want to do that using document.createElement() and .textContent.

document.createElement() takes a string of the tag name you want to create. It then returns the element.

While we're at it, let's assign a variable to the element that document.createElement() returns and add some text to it.

const h1 = document.createElement("h1")
h1.textContent = "Long time no see!"

This h1 exists in memory only. Now on the DOM. The most common way to append this to the DOM is to first select the parent, and call it's .appendChild.

const h1 = document.createElement("h1")
h1.textContent = "Long time no see!"
myGreeting.appendChild(h1)

Practice .appendChild() and document.createElement() by listing an array of string to an unordered list

Using just JavaScript, Make this array an HTML list:

const animals = ["dog", "cat", "mouse"]

Here's a complimentary ul to append to.

<ul id="list"></ul>

Final Product:

  • dog
  • cat
  • mouse

You may be asking why we wouldn't just write this in our HTML.

JavaScript helps us dynamically render our apps. We'll be using JavaScript to get us dynamic data, and then change how the webpage looks depending.

If a user wanted to take things from a list, or add to a list, we would use JavaScript to control that.

Much of your DOM manipulation will happen after the user does something. To complete what you've started in this article, making the user able to change what they see, you'll need to learn to use event listeners