JavaScript DOM Tutorial: 2020 Edition

JavaScript is an open-source programming language. It is designed for creating web-centric applications. It is lightweight and interpreted which makes it much faster than other languages. JavaScript is integrated with HTML, which makes it easier to implement JavaScript in web applications.

In this JavaScript DOM Tutorial, we will get familiar with the Document Object Model of a webpage and learn how to manipulate the DOM by creating a basic web application. JavaScript is absolutely essential for web development, and in case you want to choose web development as your career you’d surely come across this language. And probably, that’s why you are here in the first place. 

We offer complete Job Guarantee and money-back if you don't secure a job within 6 months of graduation. Get interview ready with intense and comprehensive career mentoring sessions in our Full Stack Java Developer Program. Enroll TODAY!

What is JavaScript DOM?

DOM is short for Document Object Model. JavaScript accesses the contents of a webpage making use of DOM which is created by the browser when a webpage is rendered.

javascript-dom

Fig: JavaScript DOM Tree

Document Object Model of a webpage can be represented graphically in the form of a tree. Here, the document element is <html> element, <head> tag contains headers like webpage title, and <body> tag contains contents that are displayed inside a web page. Each document can have only one document element. In an HTML document, the document element is the <html> element. JavaScript uses DOM to perform multiple functions such as creating and deleting elements on the web page. The same will be explained in detail later while creating a simple webpage in this JavaScript DOM Tutorial.

Interacting With the DOM

Interacting with a webpage is the same as interacting with its Document Object Model. Since a web browser creates DOM whenever a webpage gets rendered, you can add or remove HTML elements by manipulating the DOM itself.

/intercating.

Fig: Interacting with the DOM

You can style the elements using the CSS stylesheet, and even add user interaction by attaching event listeners, like click or submit or a keypress on the keyboard, to the HTML elements. There are several DOM methods that can be employed for these tasks. Next up? Here are some of the most basic methods in the next section where you learn to create an HTML webpage and manipulate it using JavaScript DOM.

DEMO Application

In this Demo application, a basic, but a decent-looking webpage will be created that displays a list of movies that people generally tend to like. , To this application, a few DOM manipulation methods will be added like adding and deleting elements to make this webpage a bit interactive.

html

Fig: HTML application

Prerequisites:

  • Apart from a text editor of your choice, and a web browser, we do not require anything else to get started building this application.
  • I generally prefer Visual Studio Code, but you could use any other text editor which you like.

visual-code.

Fig: Visual Studio Code

  • So to begin with this project, let’s create a new folder and open that folder in a text editor!

Code:

index.html

This file contains the HTML code that has all the contents of a webpage. 

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <link href="styles.css" rel="stylesheet" />

    <script src="app.js"></script>

    <title>MovieTime</title>

  </head>

  <body>

    <div id="wrapper">

        <header>

            <div id="page-banner">

                <h1 class="title" style="color: #fff;">MovieTime</h1>

          <p style="color: #fff;">A curated list of the most amazing movies!</p><br>

            </div>

        </header>

        <div id="movie-list">

            <h2 class="title">Movies to Watch</h2>

            <ul>

                <li>

                    <span class="name">The Intern</span>

                    <span class="delete">delete</span>

                </li>

                <li>

                    <span class="name">Inception</span>

                    <span class="delete">delete</span>

                </li>

                <li>

                    <span class="name">The Prestige</span>

                    <span class="delete">delete</span>

                </li>

                <li>

                    <span class="name">The Wolf of Wall Street</span>

                    <span class="delete">delete</span>

                </li>

            </ul>

        </div>

        <form id="add-movie">

            <input type="text" placeholder="Add a movie..." />

            <button>Add</button>

        </form>

    </div>

  </body>

</html>

  • Start by importing a script file and CSS file and add these files within the header tag so as to be accessible by all HTML elements.
  • Then, define a <div> tag that wraps the content into a box.

movies

Fig: Movies list box

  • Inside that div tag, there is a new div tag that contains the banner for this box.

banner

Fig: Banner

  • Close the banner div, and define a new div that displays the list of movies.

movie-list

Fig: Movie list

  • <ul> is for creating unnumbered lists, and <li> represents list items.
  • Add form tag to add a movie to this list and assign the form with a text input box and add a button.

html-form

Fig: HTML form element

App.js

This is the javascript file that isused for DOM manipulation, like adding or deleting an HTML element. Let’s go through what the code does. In this case,  comments have been added for each snippet of code so you know exactly what each part of the code is for.

document.addEventListener('DOMContentLoaded', function(){

    const list = document.querySelector('#movie-list ul');

    const forms = document.forms;

  

    // delete movies

    list.addEventListener('click', (e) => {

      if(e.target.className == 'delete'){

        const li = e.target.parentElement;

        li.parentNode.removeChild(li);

      }

    });

  

    // add movies

    const addForm = forms['add-movie'];

    addForm.addEventListener('submit', function(e){

      e.preventDefault();

  

      // create elements

      const value = addForm.querySelector('input[type="text"]').value;

      const li = document.createElement('li');

      const movieName = document.createElement('span');

      const deleteBtn = document.createElement('span');

  

      // add text content

      movieName.textContent = value;

      deleteBtn.textContent = 'delete';

  

      // add classes

      movieName.classList.add('name');

      deleteBtn.classList.add('delete');

  

      // append to DOM

      li.appendChild(movieName);

      li.appendChild(deleteBtn);

      list.appendChild(li);

    });

  

  })

  • first, add an event listener that loads the contents on the webpage.
  • Then add an event listener to the delete button, that deletes a list item when clicked upon.
  • Similarly,  add another event listener to the add button, that adds an item to the list.
  • For that, obtain the value from the text input using a query selector.
  • Then use createElement to create HTML elements using JS DOM.
  • Finally,  append the movie name and delete button to the li tag (list in the HTML file).

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

styles.css

Since this is not a CSS tutorial, all the styles haven’t been explained but the code is included if you want to make the webpage look exactly like the one shown here. Feel free to create your own style though.

body {

  background-image: url("bg.jpg");

  background-size: 100%;

  font-family: sans-serif;

  color: #444;

  letter-spacing: 1px;

}

 

h1,

h2 {

  font-weight: normal;

}

 

#wrapper {

  background-color: #eee;

  width: 90%;

  max-width: 960px;

  margin: 20px auto;

  border-radius: 6px;

  box-shadow: 1px 10px 10px rgba(0, 0, 0, 0.7);

  box-sizing: border-box;

  padding: 0 0 20px;

  overflow: hidden;

  border: 1px solid lightgray;

}

 

#page-banner {

  background-image: url("image-4.jpg");

  background-size: 100%;

  align-items: center;

  padding: 10px 0;

}

 

#page-banner h1,

#page-banner p {

  width: 100%;

  text-align: center;

  margin: 10px 0;

}

 

#movie-list,

#add-movie {

  margin: 30px;

}

 

#movie-list ul {

  list-style-type: none;

  padding: 0;

}

 

#movie-list li {

  padding: 20px;

  border-left: 5px solid #ddd;

  margin: 20px 10px;

}

 

#movie-list li:hover {

  border-color: #9361bf;

}

 

.delete {

  float: right;

  background: red;

  padding: 6px;

  border-radius: 4px;

  cursor: pointer;

  color: white;

}

 

.delete:hover {

  background: maroon;

}

 

#add-movie {

  width: 400px;

  margin: 0 auto;

}

 

#add-movie input {

  display: block;

  margin: 20px 0;

  padding: 10px;

  border: 1px solid #ccc;

  font-size: 16px;

  border-radius: 4px 0 0 4px;

  box-sizing: border-box;

  width: 300px;

  float: left;

  clear: both;

}

 

#add-movie button {

  border: 1px solid green;

  background: green;

  padding: 10px 20px;

  font-size: 16px;

  display: inline-block;

  margin: 0;

  border-radius: 0 4px 4px 0;

  cursor: pointer;

  width: 100px;

  float: left;

  margin: 20px 0;

  border-left: 0;

  color: white;

}

 

#add-movie button:hover {

  background: darkgreen;

}

 

#add-movie:after {

  content: "";

  display: block;

  clear: both;

}

 

#add-movie label {

  line-height: 52px;

}

This was all about the code that was required for this small web application -  It should look and feel like this in the end.

demo

Fig: DEMO Application

Hope you learned the basics of DOM manipulation and enjoyed going through this JavaScript DOM Tutorial article.

Get Ahead of the Curve and Master JavaScript today

Are you wondering how you can gain the skills necessary to take advantage of JavaScripts’ immense popularity now that you are familiar with JavaScript DOM and its manipulation? We have your back! We offer a comprehensive Java Certification Training, which will help you become career-ready upon completion. To learn more, check out our Youtube video that provides a quick introduction to JavaScript DOM and explains how to implement and manipulate DOM in a web application. If you’re an aspiring web and mobile developer, JavaScript training will broaden your skills and career horizons.

Do you have any questions for us? Please mention it in the comments section of the JavaScript DOM Tutorial and we'll have our experts answer it for you.

About the Author

Taha SufiyanTaha Sufiyan

Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.