From the course: JavaScript: Enhancing the DOM

Creating elements with createElement

From the course: JavaScript: Enhancing the DOM

Creating elements with createElement

- [Instructor] Let's take control of the DOM and learn how we can create, add, and manage nodes in the DOM. This is very important for web development, and it feels even a bit magic to bring new elements to life using JavaScript, so that's what we'll start with. To create a new element, we're going to use the method createElement, and this creates a new HTML element. For example, documents.createElement, div, conjures up a new div element right out of thin air, but that element is not automatically appearing on your page. Well, why not? Well, where should it be? And that's right. We still need to tell the DOM where to include this. We can do that with the appendChild methods on an element or by overriding innerHTML with our newly created object. Here we have a very empty webpage, but if I'm going to go ahead and I open this, you will see that this is more than the index.HTML. How so? Well, of course we created a new element and appended it to our page. And here's how that is done. On line two, we use document.createElement, p, to create a new paragraph. Then we're going to set the text content of this new paragraph, so this is new paragraph added to my JavaScript. We can also set attributes much like we've seen before, and also the style. Here, I'm just giving it an ID of newParagraph and I'm making the color of the text blue. Then the next step is very important, otherwise we won't see anything on the page. We need to append new elements to our webpage and we're going to add it to the content area. So we select the content area using the ID contentArea, and then we use the .appendChild to add the child, the new HTML element, to our page. And that's how to add HTML elements. Next up, we're going to use constructors for creating specific elements.

Contents