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!
Setup
- Make a folder/directory on your computer. Name it something appropriate, like āvanilla-js-practice.ā
- Create two files within this folder,Ā
Ā andĀindex.html
.index.js
- Next, letās add some boilerplate code to our newĀ
Ā file:index.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
document.createElement()
.textContent
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.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:
<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Ā
index.html
Ā 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.
Building Blocks #3, 4, and 5 - Ā .appendChild()
,Ā .removeChild()
, andĀ .remove()
.appendChild()
.removeChild()
.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:
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: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!
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);
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 remove myĀ
text2
Ā variable that I created above, I could do so one of two ways:document.body.removeChild(text2);
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
).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()
.setAttribute()
.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Ā 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()
.querySelector()
.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 of 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(".sampleClass");
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:
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.
Attributions:
- Jenga image 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)
Previously published at https://shinetechnicallywrites.netlify.app/posts/vanilla-js-tutorial-part-one/