Add a Node to Your HTML with document.appendChild

Ian Jones
InstructorIan Jones
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

This lesson goes over how to create an HTML element and add it to our document. We do this by creating an element with document.createElement. Once we have the element created, we can use document.appendChild to add our element to our HTML.

We then go over how to connect our JavaScript to a button's onclick event.

Instructor: [00:00] Here we have an HTML page with a list of movies. To add a movie to this list, first we need to create the list element in our JavaScript, so const UncutGems=document.createElement(). createElement takes a string, and this string is the type of element that we're creating. In this case, we want to create a list item element.

[00:32] Next, we need to set the text content to what we want. In this case, we want "Uncut Gems." Just because we have created this element in our JavaScript does not mean that it has been added to our HTML. The first thing we need to do is get a reference to this unordered list element. Now that we have a reference, we can call movies.appendChild(uncutGems).

[01:19] Let's hop over to our browser. Before we reload, we just have "Peanut Butter Falcon" and "Knives Out" because that's what was in our HTML. When we reload, the page is going to load, and our JavaScript is going to run, and it will add a third element called "Uncut Gems."

[01:38] It would be nice to have this code run when the user clicks a button rather than running automatically. Let's add a button called addUncutGems. We need to create a function called addMovie(). It's going to be an arrow function. Next, we're going to move this functionality up into our function.

[02:07] Now we need to connect this function to this HTML element. The way we can do that is we can use the elements on event handlers. One of the events that elements handle by default is onclick, which we can assign, addMovie, to when a user clicks this button.

[02:31] When we go to our browser, we now have this addUncutGems button and when we click, a list element is created for us. You can assign the onclick handler in your JavaScript directly. If we remove onclick from our HTML element, and we grab a reference to our button, so document.querySelector('button'), now that we have a reference to our button, we can go button.onclick = "addMovie()".

[03:20] Now when we reload, nah, is a bug. We don't want to call the method in our JavaScript. We want to pass a reference to our method. We reload, and now when we click, we get "Uncut Gems."