Create a User Interface with Vanilla JavaScript and DOM

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

You can create a simple user interface on the web using HTML and CSS. But as soon as you want to make your application interactive, you need to use JavaScript to manipulate the DOM (Document Object Model) to listen to user events and make updates to the user interface. In this lesson we'll learn how to create a <div> element using raw JavaScript and browser APIs.

Kent C. Dodds: [0:00] To start, we're going to need a body. Inside of here, we're going to have a div with an ID of root. That's where our application is going to be mounted. Then we'll have a script. Our type for our script is going to be text/JavaScript. Inside of here, we need to get access to this div. I'm going to make a variable called rootElement. That'll document.getElementById root.

[0:29] Then I'm going to take this rootElement and append a child. We need to append an element to this. Let's create that element with document.createElement. We'll make it a div. For this element, we want the text content to be "Hello, world." Just for fun, we'll have the element.className equal container. We'll save that and get a refresh here. Now we have "Hello, world."

[0:56] If we look at the output, we have one thing from that Browsersync, but then here is our application at the root. That's the div we created with the class name of container and the text content of "Hello, world." Then here's our JavaScript code that we wrote.

[1:11] In review, to create a user interface in JavaScript, you're going to need to have a place where you append your JavaScript-generated DOM elements. We're going to get access to that element from the document APIs. Then we'll create our own element. We'll add some properties onto that element. Then we'll append that element to our rootElement.

egghead
egghead
~ 2 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today