CJCoding With Joseph
15free / daySign inCreate account

JavaScript For Web

Creating and Removing Elements with JavaScript

In the last lesson, we learned how to change text, HTML, and styles on elements that already exist on a page. Now we are going to take that one step further and learn how to create brand new elements and remove them using JavaScript.


Creating a New Element

JavaScript can create new HTML elements while your page is running using the document.createElement() method. This allows you to build new parts of a web page without reloading or editing the original HTML file.

When you create a new element, it does not show up on the page right away. At first, it only exists in JavaScript’s memory. To make it appear, you must do three things in order:

  1. Create the element using document.createElement("tagName")

  2. Set its content using either textContent or innerHTML

  3. Attach it to an existing element (called a parent) using .appendChild()

In the example below, we will create a new paragraph each time the user clicks a button.
The steps are simple:

  • We create a new <p> element.

  • We give it some text.

  • We attach it to a container <div> so it appears on the page.

When you click the button, a brand-new paragraph appears below the existing one. You can click multiple times to add as many paragraphs as you like.

HTML File

<body>
  <div id="container">
    <p>This is the original paragraph.</p>
  </div>

  <button id="btnAdd">Add a New Paragraph</button>

  <script src="script.js"></script>
</body>
Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 10 more lessons in JavaScript For Web.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.