Technical writer in Seattle, WA
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.
Let’s get started!
<!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
section of an HTML file, we would see all sorts of elements, like
, to name a few. However, in our HTML file, the <body> section contains only a
tag and nothing else. This
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
file; every other line of code you see in this article will be in our
All right, now that we are in our
file, type the following code block into your editor, and then read on for an explanation of what you just typed.
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
. 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
to create an
element, which we then stored in
Another very important building block is
. 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 (
) 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:
<h1>Vanilla JS Practice</h1>
You would be hard-pressed to find a web developer who says that using vanilla JS is the quickest and most 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
file in your web browser to see our new header:
…Where is it? Why has it not appeared?? 😱😱😱
The short answer: It isn’t there because you haven’t told it to be there.
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
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
Here’s how we will add
to the DOM:
section of our
is a native method we can use to add the specified element (in this case,
) to the DOM. Please note that
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:
const header = document.createElement('h1'); header.textContent = 'Vanilla JS practice'; document.body.appendChild(header);
Open up your
file in your browser once more and you should see:
Good job! You have created your first element in vanilla JS, an
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!
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:
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);
Just as we can add elements to the DOM with
, we can take them away with
For example, if I wanted to remove my
variable that I created above, I could do so one of two ways:
The first way would be using
to remove an element in exactly the same way that we used
to add an element; we invoke a method at the parent level (
is the parent of
) to add or remove a child element (
Don't cry, child. Your parents won't remove you using vanilla JS!
The second way is different; it utilizes the
method instead of
. Since we aren’t referencing parent or child elements with this method, it can be called directly on the element to be removed, thus
would be our syntax.
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 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.
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
2) Adding the id “giantWalrus” to
Removing attributes with
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
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
returns the first element in the document that matches the provided selector, while
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 of lines; try them yourself first and then check your work!
1) Create a variable
that contains the first element of class
const firstElem = document.querySelector(".sampleClass");
2) Create a variable
that contains all elements of the class
const allElems = document.querySelectorAll(".classDismissed");
3) Create a variable
that contains the element with the id
4) Create a variable
that contains all
elements in the document:
Answer to #3 -
const greatId = document.querySelector("#thisIsAGreatExampleIdName");
Answer to #4 -
const divsAndPs = document.querySelectorAll("div", "p");
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:
Created HTML elements with vanilla JSAppended and removed those elements to and from the DOMSelected elements by attributes
I hope you found this helpful! Check out part 2, where we take on using vanilla JS to style content.
Previously published at https://shinetechnicallywrites.netlify.app/posts/vanilla-js-tutorial-part-one/
Create your free account to unlock your custom reading experience.