Creating New Elements

Open the project folder

In our starter files, open the index.html page from this lessons folder:

04.Events-And-The-DOM > 04.Creating-new-elements

Creating elements

Along with all the modifications we have been making to existing elements, we can also create our own. In fact, we can even create sections or a full web page of HTML content with JavaScript. This opens many doors and means our content can be more dynamic and change after the page has loaded.

The possibilities are huge, examples could be:

  • To only show content to the user if logged in.
  • We could get all the users previous orders and create a HTML list based on this information.
  • The user could add a new to-do item

document.write()

Before we create a new element, I want to show you something called document.write which writes directly to the document:

document.write('hey');

This can also contain HTML:

document.write('<h1>hey</h1>');

This method is more used for things like testing rather than adding content to the page, one of the reasons for this is because if the page has finished loading, it will override all the loaded content.

We can see this better if we delay the document.write to wait on the page fully loading.

To do this we can use a setTimeout method, don’t worry if you have never seen this, it is just a way to run a function after a certain time delay, we will discuss it further into the course:

// 1. comment out
// document.write('<h1>heeey</h1>');

// 2. add timeout
setTimeout(() => document.write('where my content go?'), 3000);

This will run after 3 seconds (3000ms) and replace the content. Meaning it is not often a good way of adding content to our page, for this we have some dedicated methods.

This example can now be removed or commented out.

Often creating elements happens in multiple parts. With a text element for example, we first create an empty <p> element, then we create the text content node, then we add the text to the element.

Recreating a section with JavaScript

In the starter file, we have this new HTML section:

<section>
  <h3>Helping the planet, one bite at a time...</h3>
  <div class="content">
    <div class="image_section">
      <img src="burger.jpg" alt="burger image" />
    </div>
    <div class="info_section">
      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Dolore aut unde sunt.
      </p>
      <button>BUY ONLINE</button>
    </div>
  </div>
</section>

To give you an idea of what we are going to do, we will re-create this using JavaScript.

The createElement method

We will create the div sections soon, along with the outer section. First we will create the content elements which is the h3, the img, the lorem ipsum text, and the button:

// ========= SECTION HEADING =========
// The createElement method creates a new element by the tag name:
const sectionHeading = document.createElement('h3');

In the console, we can check what is returned by typing our variable name of sectionHeading:

sectionHeading
<h3></h3> // empty h3 returned

This shows we have created a h3 element, but we have no content inside. Remember earlier when we looked at the DOM and said that all objects in the tree are nodes.

Creating text nodes

We now have the first part which is the element node for our h3, now we need some text content. And we can do this with a method called createTextNode:

// ========= SECTION HEADING =========
const sectionHeading = document.createElement('h3');
// create the text content:
const headingText = document.createTextNode(
  'Helping the planet, one bite at a time...'
);

You can also see this text in the console:

headingText
“Helping the planet, one bite at a time...// returned text

The appendChild method

But currently, both the h3 and the text are independent nodes, we need to add this text to the heading. And this is made possible by selecting the parent heading, and calling a method called appendChild:

const sectionHeading = document.createElement('h3');
const headingText = document.createTextNode(
  'Helping the planet, one bite at a time...'
);
sectionHeading.appendChild(headingText);

And this now completes our heading, you can also confirm this by again typing sectionHeading into the console. You will see the full heading with the text content returned.

Completing content the elements

The rest of the content is very similar:

// ========= IMAGE =========
const imageElement = document.createElement('img');
imageElement.setAttribute('src', 'burger.jpg');
imageElement.setAttribute('alt', 'burger image');

// ========= INFO TEXT =========
const infoSectionElement = document.createElement('p');
const infoSectionText = document.createTextNode(
  'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Dolore aut unde sunt.'
);
infoSectionElement.appendChild(infoSectionText);

// ========= BUTTON =========
const buttonElement = document.createElement('button');
const buttonText = document.createTextNode('BUY ONLINE');
buttonElement.appendChild(buttonText);

Creating the section wrappers

This is all of the content elements, we also need to create the wrappers too:

// ========= WRAPPERS =========
const sectionWrapper = document.createElement('section');
const contentWrapper = document.createElement('div');
const imageDivElement = document.createElement('div');
const textDivElement = document.createElement('div');

Adding the elements to the wrappers

Currently, the wrappers are all empty elements. Just like when we added the text nodes to our elements, we also need to add our elements to the wrappers:

// ========= PUTTING IT ALL TOGETHER =========
textDivElement.appendChild(infoSectionElement);
textDivElement.appendChild(buttonElement);

imageDivElement.appendChild(imageElement);

contentWrapper.appendChild(imageDivElement);
contentWrapper.appendChild(textDivElement);

sectionWrapper.appendChild(sectionHeading);
sectionWrapper.appendChild(contentWrapper);

To check we have the correct structure, we can type in sectionWrapper in the console and see all the nested content inside.

Adding the classes

To finish this HTML off, we can also match up the classes:

// ========= ADDING CLASSES =========
contentWrapper.setAttribute('class', 'content');
imageDivElement.setAttribute('class', 'image_section');
textDivElement.setAttribute('class', 'info_section');

This is all now in place and the next thing to do is to look at the ways we can add this new section to our page.