JavaScript Essential Training
Illustration by Mark Todd

Creating DOM elements


JavaScript Essential Training

with Simon Allardice

Watch every course in the library with a membership.
Each course includes high-quality videos taught by expert instructors.

Start Your Free Trial Now

Video: Creating DOM elements

While you could use the innerHTML method to just write out a bunch of HTML and dump it into a position in your document, it's not a clean way to do it, and it's easy to make a mistake. The best way is to start manually creating and inserting individual DOM element nodes into your document, and this is a very powerful technique to learn. It lets you change your page on the fly and to do it, there's always two steps. One, you create the element. You say I want to create a paragraph or a heading or a list item or an anchor tag.
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye

please wait ...
Watch the Online Video Course JavaScript Essential Training
5h 31m Beginner Jul 22, 2011

Viewers: in countries Watching now:

Use JavaScript to add new features and a richer, more compelling user interface on web pages. This course keeps current best practices and practical uses for JavaScript in mind, while covering syntax, working with the DOM, and developing and debugging across multiple platforms, devices, and browsers. Author Simon Allardice also shows how to progressively enhance and gracefully degrade web pages, and take advantage of the world of JavaScript libraries now available.

Topics include:
  • Understanding the structure of JavaScript code
  • Creating variables, functions, and loops
  • Writing conditional code
  • Sending messages to the console
  • Working with different variable types and objects
  • Creating and changing DOM objects
  • Event handling
  • Working with timers
  • Debugging JavaScript
  • Building smarter forms
  • Working with CSS, HTML5, and JavaScript
  • Using regular expressions
Developer Web
Simon Allardice

Creating DOM elements

While you could use the innerHTML method to just write out a bunch of HTML and dump it into a position in your document, it's not a clean way to do it, and it's easy to make a mistake. The best way is to start manually creating and inserting individual DOM element nodes into your document, and this is a very powerful technique to learn. It lets you change your page on the fly and to do it, there's always two steps. One, you create the element. You say I want to create a paragraph or a heading or a list item or an anchor tag.

And step two is you then add that newly created element to the right place in the DOM, the right place in the document. So here's an example. If I imagine I've got a very simple HTML page representing here as a set of DOM nodes, I can see that my body consists of three things: an h1 heading, a paragraph, and an unordered list with an id of abc. That unordered list has three list items underneath it. And I can imagine I've already used getElementById to create a variable called myElement that points to that unordered list.

That will be important in a second. So if I want to add a new list item to this point in the DOM, a new list item to the unordered list, what I have to do is first, step one, create the element. And instead of using document.getElementById, we use document.createElement and I pass in a string that says what kind of element. In this case, it's an li. If I wanted a paragraph, it would be a p; if I wanted an anchor tag, it would be an a; and so on. Now that creates it, but it creates it kind of out there in space.

The element exists, but it's not part of the DOM itself. So the next thing that I need to do, step two, is call the appendChild method of myElement. So I'm actually saying for the unordered list, append the child this new element, the list item. JavaScript will take it. It will make it part of the DOM and understand its place in the document itself. Now right now, this list item would be a little bit basic because we haven't set it. We haven't given it any text, and that's usually what we expect with a list item.

Well, I could, if I wanted, use innerHTML and just actually set the text of the list item. And that would work, but there is a preferable way to do it as well, or a more exact way, which is that after we've created the element itself, we then create a text node. Remember that the element and the text they contain are actually different. So if I've got that variable myNewElement that points to that list item, what I'm then going to do is use the createTextNode method, which creates this text node. Very similar to creating an element, it's out there in space, not attached to anything.

And once again, we use appendChild, except this time we're adding it to the NewElement. This would be the most exact, the most specific way to start creating these DOM elements. So let's do a demo. So in my browser, I have a page that I already created. It's just a fairly regular web page. But down here a little bit further, I've got this area that I want to generate some content in, and I'm actually going to do that using JavaScript. This blank area here, if I look at my HTML, is actually represented by a div with an id of trivia.

So this is the place that I want to create new DOM elements and add them right here. So the way to do it, if I come over to my script.js file, I've got some code that already exists. I'm just going to uncomment it. And I'm actually going to do two things here: I'm going to create an h1 element, and then I'm going to create a p, or paragraph, element. So lines 2 and 3 we actually create new variables creating those elements, but they're just existing out there in space. They actually aren't part of the page yet. Well, not only that, they don't have any content.

So if I want to do the slightly easier way but not as exact as possible, we could call the innerHTML on both of these new variables. So newHeading, which I just created, set its innerHTML to "Did You Know?" And the newParagraph, which I just created, set its innerHTML to "California produces over 17 million gallons of wine each year." So we have our elements, we have some text added to them, but they're still not part of the page. And in fact, right down here on Line 17 and 18 I'm just going to uncomment these lines because this is how we add them to the page.

If you remember, the div that I wanted to add them to is called trivia. So we call document.getElementById ("trivia").appendChild(newHeading), we're adding the h1, and then we call the whole thing again, and then we say we'll now append another child, which is the paragraph. So if I save this and I just open that up in the browser again, what we'll find is that that part of the page that was blank now has this content that's been dynamically added. And because it's using the same CSS rules as the rest of the page, I have a formatted headline with the underline and I have the correct font showing up.

But let's just talk about the more exact way of adding text. We can use innerHTML, but the alternative way is going to be below here. It's going to require two more lines of code, but it is a bit more exact. And we do it similar to creating the elements themselves. We actually create new text nodes. So on Line 10, I'm creating a variable called h1Text and calling document.createTextNode and giving it a little bit of text to initialize itself, and then the same thing on Line 11 for the paragraph.

But because you create text nodes just like elements that are just existing disconnected out in space, what I'm then doing is on Line 13 and 14 I'm associating those new text nodes with the new h1 and the new paragraph that I created on Line 2 and 3. And I'm leaving line 17 and 18 exactly as they are because we still need to add the new heading and new paragraph to our DOM. Save that, jump back over into the browser, and if I refresh this, we should see absolutely no changes at all.

Again, you can make your own decisions about which method to use. Creating text nodes separately does mean typically writing a little bit more code, but it is a more exact and more specific way to do it. So while the process is always going to be a step one, create the element, step two, add it to the DOM, there is an alternative to appendChild, although that is the most common one. Instead of just pointing to the parent element and saying appendChild, we also have the choice of insertBefore. So if you want a bit more flexibility about where our new element is inserted into the DOM, we can use this one as well.

Let me show an example here. So taking the same idea of that DOM tree that we had before, appendChild will always add that new list item right at the end. It will always add it, as in this case, the fourth list item. But what if I didn't want that? Well, step one is still the same: create the element. We're creating it there out in space. Now the second step here is I need to grab hold of a variable that points to, in this case, let's say the second list item, and I'm going to do this by calling getElementsByTagName, because that second list item doesn't have an ID.

So I'm first calling myElement.getElementsByTagName, saying I want to find all the list under the unordered list. And then I'm using the square brackets and saying number one, which if you remember, we're going to use zero-based arrays, so the first one would be at position 0, the second one at position 1, the third one at position 2. So I now have a variable, secondItem, that points to the second list item. And what I can do is use the other way of adding to the DOM.

Instead of appendChild, I call myElement.insertBefore and the two pieces of information I give it is what's the new element and what's the element you want to insert it before, in this case, secondItem, at which point it will reshuffle that arrangement and insert my new list item into that very specific point in the DOM. So most of the time, you'll be using appendChild, but insertBefore can come in very handy as well.

There are currently no FAQs about JavaScript Essential Training.


Learn to Code with Hands-On Practice

Code practice

In one click, you can now launch the beta Code Practice window to easily work with the files from the videos. No downloading or software required! Work along with your course in real time with this new in-browser coding environment

Practice environment

No, thanks!
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.