Vanilla JS Tutorial - Part One
Building blocks of the DOM
Tags: javascript
Published: 2021-04-11 17:01:06

This post is the first part of a code-along tutorial, where you'll learn some rudimentary skills in vanilla JS DOM manipulation. If you missed my previous entry, where I discussed what vanilla JS is and why it's important, check it out [here](https://shinetechnicallywrites.netlify.app/posts/lets-talk-about-vanilla-js/).

Let's get started!

### Setup

1) Make a folder/directory on your computer. Name it something appropriate, like "vanilla-js-practice."
2) Create two files within this folder, `index.html` and `index.js`.
3) Next, let's add some boilerplate code to our new `index.html` file:

```html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title> Vanilla JS Practice </title>
  </head>
  <body>
    <script src="index.js"></script>
  </body>
</html>
```

Normally, in the `<body>` section of an HTML file, we would see all sorts of elements, like `<h1>`, `<h2>`, `<div>`, and `<p>`, to name a few. However, in our HTML file, the `<body>` section contains only a `<script>` tag and nothing else. This `<script>` tag essentially tells the web browser to read the `index.js` file for valid code to run.

This is the last time we will touch our `index.html` file; every other line of code you see in this article will be in our `index.js` file.

### Building Blocks #1 & 2 - `document.createElement()` and `.textContent`

![pile of blue legos](https://i.imgur.com/RZYHhmL.jpg)

All right, now that we are in our `index.js` file, type the following code block into your editor, and then read on for an explanation of what you just typed.

```javascript
const header = document.createElement('h1');
header.textContent = 'Vanilla JS practice';
```

Perhaps the most important snippet of code to remember when using vanilla JS for DOM manipulation is `document.createElement()`. Put simply, this is the code you use to create an HTML element. The HTML element you want to create goes inside the parentheses in quotation marks. In our example, we used `document.createElement('h1')` to create an `<h1>` element, which we then stored in `header`.

Another very important building block is `.textContent`. As you may have deduced, this is the property that allows us to set or change the text of an element. In the second line of our example, we take the element that we created in the previous line (`header`) and set its text to `Vanilla JS practice`.

Whew! That was kind of a lot of explanation for something that simple. Using vanilla JS to write HTML code ends up being quite a bit lengthier than just writing the HTML itself. The HTML equivalent of our two lines of vanilla JS above would be:

```html
<h1>Vanilla JS Practice</h1>
```

You would be hard-pressed to find a web developer who says that using vanilla JS is the most quick and concise way to write code. However, remember that you're learning this not because it's the quickest or most elegant way to code. You're learning this because it is a great way to remove layers of abstraction and really understand the mechanics of the language and the DOM. So, on we go!

Okay, time to see what we've got so far. Open up your `index.html` file in your web browser to see our new header:

...Where is it? Why has it not appeared?? 😱😱😱
![despairing Psyduck](https://media.giphy.com/media/hQ0GvkpZwYcgM/giphy.gif)

The short answer: _It isn't there because you haven't told it to be there_.

![surprised Pikachu face](https://en.meming.world/images/en/thumb/2/2c/Surprised_Pikachu_HD.jpg/300px-Surprised_Pikachu_HD.jpg)

### Building Blocks #3, 4, and 5 - `.appendChild()`, `.removeChild()`, and `.remove()`

Don't worry, you haven't made a mistake! This is an important distinction between HTML and vanilla JS. In HTML, under normal circumstances, any elements with proper syntax in between the `<body>` tags will render to the DOM. When using vanilla JS, this is not the case; we have to intentionally add each element we create to the DOM. Kind of a pain, don't you think? It's one of the reasons why using vanilla JS for an entire project isn't generally advisable unless you are doing it for the sake of practice, like we are.

Anyway, this is where `.appendChild()` comes in.

Here's how we will add `header` to the DOM:

`document.body.appendChild(header)`

`Document.body` references the `<body>` section of our `index.html` file, and `appendChild` is a native method we can use to add the specified element (in this case, `header`) to the DOM. Please note that `appendChild` adds the specified element to the DOM **below** any previously appended elements.

Now then, the three lines of code we should have typed out in our code editor so far are as follows:

```javascript
const header = document.createElement('h1');
header.textContent = 'Vanilla JS practice';
document.body.appendChild(header);
```

Open up your `index.html` file in your browser once more and you should see:

![Text vanilla js practice on a white background](https://i.imgur.com/YblptHE.jpg)

Good job! You have created your first element in vanilla JS, an `<h1>` header.

Let’s try to create a little bit more. Use the steps we took to create and append the header to create some text below your header. Try this on your own, and then scroll below if you need some guidance or to compare your efforts to mine. Good luck, you can do this!

![cat furiously pawing computer keyboard](https://media.giphy.com/media/unQ3IJU2RG7DO/giphy.gif)

How did you do? Hopefully you were able to add some text below your header. More importantly, I hope you are at least a little more solid now in your understanding of JS, HTML, and the DOM, compared to where you were before you scrolled all the way down here. 

Here’s what I did as my text addition: 

```javascript
const header = document.createElement('h1');
header.textContent = 'Vanilla JS practice';
document.body.appendChild(header);

const text1 = document.createElement('p');
text1.textContent = 'Go hang a salami, I\'m a lasagna hog.';
document.body.appendChild(text1);

const text2 = document.createElement('p');
text2.textContent = 'Read the previous sentence backwards.';
document.body.appendChild(text2);
```

![same heading as before with text below](https://i.imgur.com/IPpkuDE.jpg)

Nicely done!

Just as we can add elements to the DOM with `appendChild`, we can take them away with `removeChild`.

For example, if I wanted to to remove my `text2` variable that I created above, I could do so one of two ways:

1) `document.body.removeChild(text2);`
2) `text2.remove();`

The first way would be using `removeChild` to remove an element in exactly the same way that we used `appendChild` to add an element; we invoke a method at the parent level (`document.body` is the parent of `text2`) to add or remove a child element (`text2`).

<img src="https://i.imgur.com/IWz3oMe.jpg" alt="crying toddler" height="400">
Don't cry, child. Your parents won't remove you using vanilla JS!

The second way is different; it utilizes the `remove` method instead of `removeChild`. Since we aren't referencing parent or child elements with this method, it can be called directly on the element to be removed, thus `text2.remove()` would be our syntax.

### Building Blocks #6 & 7 - `.setAttribute()` and `.removeAttribute()`

The process of labeling elements in certain ways and then using those labels to access or modify those elements is essential in web development. In HTML, the three "label types" that we have are types, classes, and ids. If you are just hearing about this for the first time, [click here](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors) and take a few minutes to learn about these labels (more accurately called selectors).

We can use vanilla JS to set and remove these attributes. `.setAttribute()` requires two arguments; the attribute to be set and the name of the attribute.

Let's look at some examples.

1) Adding the class "palindrome" to `text1`:

`text1.setAttribute("class", "palindrome");`

2) Adding the id "giantWalrus" to `text2`:

`text2.setAttribute("id", "giantWalrus");`

Removing attributes with `.removeAttribute()` works in almost the same way, except when removing the value of the selector doesn't need to be specified. For example, to remove the id "giantWalrus" from `text2`:

`text2.removeAttribute("id");`

### Building Blocks #8 & 9 - `.querySelector()` and `.querySelectorAll()`

Now that we have learned how to use vanilla JS to set attributes onto our elements, we probably ought to know how to access them through their attributes too.

The methods we use for accessing elements by attribute are `.querySelector()` and `.querySelectorAll()`. `.querySelector()` returns the first element in the document that matches the provided selector, while `.querySelectorAll()` returns all matching elements, in the form of a NodeList. A NodeList is similar to an array, but with fewer available methods.

For either of these methods, more than one attribute can be provided as a criteria; additional attributes are separated by commas.

Let's look at some examples. The answers to #1 and #2 are provided below the prompt. The answers for #3 and #4 are down a couple lines; try them yourself first and then check your work!

1) Create a variable `firstElem` that contains the first element of class `sampleClass`:

`const firstElem = document.querySelector(".myClass");`

2) Create a variable `allElems` that contains all elements of the class `classDismissed`:

  `const allElems = document.querySelectorAll(".classDismissed");`

3) Create a variable `greatId` that contains the element with the id `thisIsAGreatExampleIdName;`

4) Create a variable `divsAndPs` that contains all `<div>` and `<p>` elements in the document:

---

Answer to #3 - `const greatId = document.querySelector("#thisIsAGreatExampleIdName");`

Answer to #4 - `const divsAndPs = document.querySelectorAll("div", "p");`


### Conclusion

Great work, you made it to the end of part 1! You learned about vanilla JS, why it is worth spending time on, and got some hands-on practice. In this tutorial, you:

1. Created HTML elements with vanilla JS
2. Appended and removed those elements to and from the DOM
3. Selected elements by attributes

I hope you found this helpful! Check out part 2 soon, where we take on using vanilla JS to style content.

---

_Attributions_:

- Jenga photo by Nathan Dumlao (Unsplash)
- Vanilla ice cream cone image by Dana DeVolk (Unsplash)
- Blue blocks image by Iker Urteaga (Unsplash)
- Psyduck gif credited to The Pokémon Company International, Inc.
- Surprised pikachu face image credited to The Pokémon Company International, Inc.
- Cat mashing keyboard gif by @AaronsAnimals (Giphy)
- Crying toddler image by Arwan Sutanto (Unsplash)