10

Building Blocks of DOM Manipulation - Vanilla JS Tutorial (Part One)

 3 years ago
source link: https://hackernoon.com/building-blocks-of-dom-manipulation-vanilla-js-tutorial-part-one-dy54356y
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Building Blocks of DOM Manipulation - Vanilla JS Tutorial (Part One)

@shinetechnicallywritesMike Shine

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.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Let’s get started!

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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:
<!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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Building Blocks #1 & 2 -

document.createElement()
 and
.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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
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
.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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'.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
<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!

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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:
0 reactions
heart.png
light.png
money.png
thumbs-down.png

…Where is it? Why has it not appeared?? 😱😱😱

0 reactions
heart.png
light.png
money.png
thumbs-down.png

The short answer: It isn’t there because you haven’t told it to be there.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Anyway, this is where 

.appendChild()
 comes in.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Here’s how we will add 

header
 to the DOM:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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

0 reactions
heart.png
light.png
money.png
thumbs-down.png
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:
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Good job! You have created your first element in vanilla JS, an 

<h1>
header.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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!

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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. 

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Here’s what I did as my text addition: 

0 reactions
heart.png
light.png
money.png
thumbs-down.png
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!

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Just as we can add elements to the DOM with 

appendChild
, we can take them away with 
removeChild
.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

For example, if I wanted to remove my 

text2
 variable that I created above, I could do so one of two ways:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
  • 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
).
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Don't cry, child. Your parents won't remove you using vanilla JS!

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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 and take a few minutes to learn about these labels (more accurately called selectors).

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Let’s look at some examples.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

1) Adding the class “palindrome” to 

text1
:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
text1.setAttribute("class", "palindrome");

2) Adding the id “giantWalrus” to 

text2
:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
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
:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
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.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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!

0 reactions
heart.png
light.png
money.png
thumbs-down.png

1) Create a variable 

firstElem
 that contains the first element of class
sampleClass
:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
const firstElem = document.querySelector(".sampleClass");

2) Create a variable 

allElems
 that contains all elements of the class
classDismissed
:
0 reactions
heart.png
light.png
money.png
thumbs-down.png
const allElems = document.querySelectorAll(".classDismissed");

3) Create a variable

 greatId
 that contains the element with the id
thisIsAGreatExampleIdName
;
0 reactions
heart.png
light.png
money.png
thumbs-down.png

4) Create a variable 

divsAndPs
 that contains all 
<div>
 and 
<p>
 elements in the document:
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Answer to #3 - 

const greatId = document.querySelector("#thisIsAGreatExampleIdName");
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Answer to #4 - 

const divsAndPs = document.querySelectorAll("div", "p");
0 reactions
heart.png
light.png
money.png
thumbs-down.png

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:

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Created HTML elements with vanilla JSAppended and removed those elements to and from the DOMSelected elements by attributes

0 reactions
heart.png
light.png
money.png
thumbs-down.png

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

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Attributions:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
  • 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/

0 reactions
heart.png
light.png
money.png
thumbs-down.png
6
heart.pngheart.pngheart.pngheart.png
light.pnglight.pnglight.pnglight.png
boat.pngboat.pngboat.pngboat.png
money.pngmoney.pngmoney.pngmoney.png
Share this story
Join Hacker Noon

Create your free account to unlock your custom reading experience.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK