← Back

CREATING AND REMOVING ELEMENTS IN THE DOM

This note explains how to create elements, add them to the page, remove them, and use innerHTML and insertAdjacentHTML() in simple language.

The DOM API lets JavaScript create elements in memory, insert them into the DOM tree, remove them, and work with HTML strings when needed.

1. Big picture

When working with the DOM, there are two main ways to add content:

  1. create real DOM elements with JavaScript
  2. create HTML as a string and let the browser parse it

Diagram 1. Two ways to add content

Way 1:
createElement()
|
v
real DOM element
|
v
append / prepend

Way 2:
HTML string
|
v
innerHTML / insertAdjacentHTML()
|
v
browser parses string into DOM

Explanation

The first way works with real objects.

The second way works with strings that contain tags.

2. Creating elements

To create a new element, use:

document.createElement(tagName)

This method:

Example

const heading = document.createElement("h1");

Diagram 2. What createElement() does

document.createElement("h1")
|
v
new <h1> element
|
v
exists in memory
|
v
not in page yet

Explanation

After creation, the element already exists as an object, but the user still cannot see it on the page.

3. Changing the new element before inserting it

After the element is created, you can immediately change its properties before adding it to the DOM. For example, you can change:

Example

const heading = document.createElement("h1");
heading.classList.add("title");
heading.textContent = "This is a heading";

console.log(heading); // <h1 class="title">This is a heading</h1>

const image = document.createElement("img");
image.src = "https://nikitagoluban.eu/images/preview.jpg";
image.alt = "Preview image";

console.log(image); // <img src="https://nikitagoluban.eu/images/preview.jpg" alt="Preview image" />

Diagram 3. Create first, configure second

create element
|
v
set class
set text
set src
set alt
|
v
element is ready
|
v
insert into DOM later

Explanation

This is a very important pattern:

create -> configure -> insert

It keeps your code organized.

4. Why created elements are not visible immediately

Just because an element exists in memory does not mean it is already part of the page.

A created element becomes visible only after it is inserted into an element that already exists in the DOM tree.

Diagram 4. Memory vs DOM

Created element
|
v
memory only
|
v
not visible yet

Insert into DOM
|
v
becomes part of page
|
v
visible

5. Adding elements with append()

To add a created element to the end of another element, use:

elem.append(el1, el2, ...)

This adds one or more elements after all existing children of elem.

Example

const list = document.querySelector(".list");
const item = document.createElement("li");
item.textContent = "New item";

list.append(item);

Diagram 5. append()

list
|
+-- old child 1
+-- old child 2
`-- old child 3

append(new item)
|
v
list
|
+-- old child 1
+-- old child 2
+-- old child 3
`-- new item

Explanation

append() puts the new element at the end.

6. Adding elements with prepend()

To add an element to the beginning of another element, use:

elem.prepend(el1, el2, ...)

This adds one or more elements before all existing children of elem.

Example

const list = document.querySelector(".list");
const item = document.createElement("li");
item.textContent = "First item";

list.prepend(item);

Diagram 6. prepend()

list
|
+-- old child 1
+-- old child 2
`-- old child 3

prepend(new item)
|
v
list
|
+-- new item
+-- old child 1
+-- old child 2
`-- old child 3

Explanation

prepend() puts the new element at the beginning.

7. append() and prepend() can also add strings

These methods can accept not only elements, but also strings.

If you pass a string, JavaScript adds it as a text node.

Example

const box = document.querySelector(".box");
box.append("Hello");

Diagram 7. Adding a string

append("Hello")
|
v
text node is created
|
v
added into the element

Explanation

This is text, not HTML parsing.

So if you append a string with angle brackets, it will be treated as text unless you use innerHTML or insertAdjacentHTML().

8. The same element cannot be in two places

A DOM element cannot exist in two places at the same time.

If you append an element that is already in the DOM, JavaScript removes it from the old place and moves it to the new place.

Diagram 8. One element, one place

item is inside listA
|
v
append(item) into listB
|
v
item is removed from listA
|
v
item appears in listB

Explanation

This is not copying.

This is moving.

9. Removing elements

To remove an element from the DOM, use:

element.remove()

It is called on the element that should disappear.

Example HTML

<p class="text">Random text content</p>

Example JavaScript

const text = document.querySelector(".text");
text.remove();

Diagram 9. Removing an element

Before:
DOM contains <p class="text">

text.remove()
|
v

After:
element is gone from DOM

Explanation

After removal, the element is no longer part of the page.

10. innerHTML

innerHTML is another way to add content.

Instead of creating elements one by one, you give the browser a string with HTML tags. The browser parses that string and creates DOM elements from it.

Diagram 10. innerHTML idea

HTML string
|
v
browser parses it
|
v
real DOM nodes are created

Explanation

This is often shorter than creating each element manually.

11. Reading innerHTML

The innerHTML property stores the content of an element, including tags, as a string. The returned value is valid HTML code.

Example

const box = document.querySelector(".box");
console.log(box.innerHTML);

Diagram 11. Reading innerHTML

<div class="box">
  <p>Hello</p>
</div>

box.innerHTML
|
v
"<p>Hello</p>"

12. Changing innerHTML

If you assign a string with HTML tags to innerHTML, the browser parses that string and inserts the new content into the element. If you assign an empty string, the content is cleared.

Example

const box = document.querySelector(".box");
box.innerHTML = "<h2>Title</h2><p>Text</p>";

Example of clearing

box.innerHTML = "";

Diagram 12. Changing innerHTML

box.innerHTML = "<h2>Title</h2><p>Text</p>"
|
v
old content removed
|
v
new content created from string

13. Very important warning about innerHTML

When you assign a new value to element.innerHTML, the browser completely removes and recreates all descendants of that element. That means even old content that already existed is rebuilt again.

This causes extra work and can be bad when you only want to add a small piece of content.

Diagram 13. Why innerHTML can be expensive

element already has content
|
v
element.innerHTML = new value
|
v
old descendants removed
|
v
new descendants created again

Explanation

This is why innerHTML is not always the best tool for adding small extra content to existing markup.

14. Creating markup from an array with map() and join()

A common pattern is:

  1. take an array of data
  2. use map() to create HTML strings
  3. use join() to turn the array of strings into one big string
  4. assign it to innerHTML

Example

const fruits = ["Apple", "Banana", "Orange"];

const markup = fruits
  .map(fruit => `<li>${fruit}</li>`)
  .join("");

const list = document.querySelector(".list");
list.innerHTML = markup;

Diagram 14. Array to HTML string

["Apple", "Banana", "Orange"]
|
v
map()
|
v
["<li>Apple</li>", "<li>Banana</li>", "<li>Orange</li>"]
|
v
join("")
|
v
"<li>Apple</li><li>Banana</li><li>Orange</li>"
|
v
list.innerHTML = markup

Explanation

map() returns an array, so join() is needed before putting the result into innerHTML.

15. insertAdjacentHTML()

insertAdjacentHTML() is a modern method for adding HTML strings before, after, or inside an element without fully recreating all of its content.

It solves the main innerHTML problem when you only want to insert extra markup into existing content.

Syntax

element.insertAdjacentHTML(position, string)

Diagram 15. Main idea of insertAdjacentHTML()

existing element
|
v
insert HTML string at one exact position
|
v
keep the rest of content as it is

Explanation

This is often better than rewriting the entire innerHTML just to add one more element.

16. The four positions of insertAdjacentHTML()

The position argument can be one of four values:

Diagram 16. Four positions

beforebegin
<div class="box">
  afterbegin
  existing content
  beforeend
</div>
afterend

Explanation

Read it like this:

17. Understanding each position

beforebegin

new HTML
|
v
before the element itself

afterbegin

new HTML
|
v
inside the element
|
v
before all children

beforeend

new HTML
|
v
inside the element
|
v
after all children

afterend

new HTML
|
v
after the element itself

Diagram 17. Four-position memory trick

Outside before -> beforebegin
Inside top     -> afterbegin
Inside bottom  -> beforeend
Outside after  -> afterend

Explanation

This is the easiest way to remember them.

18. Example with beforeend

const list = document.querySelector(".list");
list.insertAdjacentHTML("beforeend", "<li>New item</li>");

Explanation

This adds the new <li> inside .list, after the old children.

Diagram 18. beforeend

<ul class="list">
  old items
</ul>

insertAdjacentHTML("beforeend", "<li>New item</li>")
|
v
new item appears at the end inside <ul>

19. Example with afterbegin

const list = document.querySelector(".list");
list.insertAdjacentHTML("afterbegin", "<li>First item</li>");

Diagram 19. afterbegin

<ul class="list">
  old items
</ul>

insertAdjacentHTML("afterbegin", "<li>First item</li>")
|
v
new item appears at the beginning inside <ul>

20. Example with beforebegin and afterend

const box = document.querySelector(".box");

box.insertAdjacentHTML("beforebegin", "<h2>Title before box</h2>");
box.insertAdjacentHTML("afterend", "<p>Text after box</p>");

Important note

The positions "beforebegin" and "afterend" work only if the element is already in the DOM tree. Otherwise, JavaScript does not know where before and after should be.

Diagram 20. Outside positions

beforebegin
|
v
outside, before element

afterend
|
v
outside, after element

21. append() / prepend() vs innerHTML vs insertAdjacentHTML()

Here is the simplest comparison:

append() / prepend()

innerHTML

insertAdjacentHTML()

Diagram 21. Which tool to choose

Need real DOM objects?
-> createElement() + append/prepend

Need to replace all content?
-> innerHTML

Need to add HTML to existing content?
-> insertAdjacentHTML()

22. Common beginner mistakes

Mistake 1. Thinking createElement() puts the element on the page

It does not. It creates the element only in memory.

Mistake 2. Forgetting to insert the created element

You must still use:

Mistake 3. Thinking the same element can stay in two places

It cannot. If you insert it somewhere else, it moves.

Mistake 4. Using innerHTML += ... too often

This can cause unnecessary rebuilding of old content.

Mistake 5. Forgetting the meaning of insertAdjacentHTML() positions

Use the four-position rule carefully.

Diagram 22. Common mistakes summary

createElement() != visible on page
append/prepend = needed for insertion
one element = one place only
innerHTML = rebuilds descendants
insertAdjacentHTML() = position matters

23. Easy memory rules

createElement() = create in memory
append() = add at end
prepend() = add at beginning
remove() = delete element
innerHTML = replace content with HTML string
insertAdjacentHTML() = insert HTML string at exact place

24. Quick summary

25. Final conclusion

If you understand these ideas:

createElement()
append() / prepend()
remove()
innerHTML
insertAdjacentHTML()

then you already have a strong base for creating and removing elements in the DOM.

This topic is very important because real web pages constantly:

26. Examples

Each example below shows one practical way to create, insert, remove, or build elements with JavaScript.

Example 1. Create and insert list items

Usernames

  • Aaron
<div class="ex1-list-example">
  <div>
    <h1>Usernames</h1>
    <ul class="ex1-usernames">
      <li>Aaron</li>
    </ul>

    <style>
      .ex1-list-example {
        margin: 24px 0;
        padding: 0 15px;
      }

      .ex1-list-example .ex1-usernames li {
        padding: 8px;
        border: 2px dashed tomato;
        text-transform: uppercase;
      }

      .ex1-list-example .ex1-usernames li:not(:last-child) {
        margin-bottom: 12px;
      }
    </style>

    <script>
      (function () {
        const wrapper = document.currentScript.closest(".ex1-list-example");
        const list = wrapper.querySelector(".ex1-usernames");

        const lastItem = document.createElement("li");
        lastItem.textContent = "Benjamin";
        list.append(lastItem);

        const firstItem = document.createElement("li");
        firstItem.textContent = "Samuel";
        list.prepend(firstItem);
      })();
    </script>
  </div>
</div>

Conclusion: This example shows how JavaScript can create new elements and add them to the beginning and the end of a list. It demonstrates createElement(), append(), and prepend() in a practical way.

Example 2. Remove an element

This text will be removed by JavaScript.

<div class="ex2-remove-example">
  <div>
    <p class="ex2-text">This text will be removed by JavaScript.</p>

    <style>
      .ex2-remove-example {
        font-family: sans-serif;
      }
    </style>

    <script>
      (function () {
        const wrapper = document.currentScript.closest(".ex2-remove-example");
        const text = wrapper.querySelector(".ex2-text");

        if (text) {
          text.remove();
        }
      })();
    </script>
  </div>
</div>

Conclusion: This example demonstrates how to remove an element from the page with JavaScript. It shows the use of remove() after selecting an element from the DOM.

Example 3. Read HTML with innerHTML

Article title

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolore, ipsa quibusdam! Praesentium accusantium fugiat distinctio quidem minima fugit eos, veniam, nam laboriosam deleniti nisi qui neque explicabo perspiciatis, consectetur non.

Read more
<div class="ex3-article-example">
  <div>
    <article class="ex3-article">
      <h2 class="ex3-title">Article title</h2>
      <p class="ex3-text">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolore, ipsa quibusdam!
        <strong>Praesentium</strong> accusantium fugiat distinctio quidem minima fugit eos,
        veniam, nam laboriosam deleniti nisi qui neque explicabo perspiciatis, consectetur non.
      </p>
      <a class="ex3-link" href="https://nikitagoluban.eu">Read more</a>
    </article>

    <style>
      .ex3-article-example {
        margin: 16px 0;
        font-family: sans-serif;
      }
    </style>

    <script>
      (function () {
        const wrapper = document.currentScript.closest(".ex3-article-example");
        const article = wrapper.querySelector(".ex3-article");
        console.log(article.innerHTML);

        const title = wrapper.querySelector(".ex3-article .ex3-title");
        console.log(title.innerHTML);

        const text = wrapper.querySelector(".ex3-article .ex3-text");
        console.log(text.innerHTML);

        const link = wrapper.querySelector(".ex3-article .ex3-link");
        console.log(link.innerHTML);
      })();
    </script>
  </div>
</div>

Conclusion: This example focuses on innerHTML. It shows how JavaScript can read the HTML content inside an element and log the contents of the whole article and its separate parts.

Example 4. Replace HTML with innerHTML

Article title

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolore, ipsa quibusdam! Praesentium accusantium fugiat distinctio quidem minima fugit eos, veniam, nam laboriosam deleniti nisi qui neque explicabo perspiciatis, consectetur non.

Read more
<div class="ex4-title-example">
  <div>
    <article class="ex4-article">
      <h2 class="ex4-title">Article title</h2>
      <p class="ex4-text">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolore, ipsa quibusdam!
        <strong>Praesentium</strong> accusantium fugiat distinctio quidem minima fugit eos,
        veniam, nam laboriosam deleniti nisi qui neque explicabo perspiciatis, consectetur non.
      </p>
      <a class="ex4-link" href="https://nikitagoluban.eu">Read more</a>
    </article>

    <style>
      .ex4-title-example {
        margin: 16px 0;
      }

      .ex4-accent {
        color: tomato;
        text-decoration: underline;
      }
    </style>

    <script>
      (function () {
        const wrapper = document.currentScript.closest(".ex4-title-example");
        const article = wrapper.querySelector(".ex4-article");
        console.log(article.innerHTML);

        const title = wrapper.querySelector(".ex4-article .ex4-title");
        console.log(title.innerHTML);

        const text = wrapper.querySelector(".ex4-article .ex4-text");
        console.log(text.innerHTML);

        const link = wrapper.querySelector(".ex4-article .ex4-link");
        console.log(link.innerHTML);

        title.innerHTML = 'New and <span class="ex4-accent">improved</span> title';
      })();
    </script>
  </div>
</div>

Conclusion: This example shows how innerHTML can also be used to replace existing HTML. It demonstrates updating a title and inserting a styled span element inside it.

Example 5. Create markup from an array

Popular technologies

    <div class="ex5-tech-example">
      <div>
        <section>
          <h2>Popular technologies</h2>
          <ul class="ex5-list"></ul>
        </section>
    
        <style>
          .ex5-tech-example {
            padding: 16px;
          }
    
          .ex5-tech-example .ex5-list {
            padding: 0;
            margin: 0;
            list-style-type: none;
          }
    
          .ex5-tech-example .ex5-list-item {
            padding: 8px;
            border-width: 2px;
            border-style: dashed;
          }
    
          .ex5-tech-example .ex5-list-item:nth-child(even) {
            border-color: tomato;
          }
    
          .ex5-tech-example .ex5-list-item:nth-child(odd) {
            border-color: blueviolet;
          }
    
          .ex5-tech-example .ex5-list-item:not(:last-child) {
            margin-bottom: 8px;
          }
        </style>
    
        <script>
          (function () {
            const wrapper = document.currentScript.closest(".ex5-tech-example");
            const technologies = ["HTML", "CSS", "JavaScript", "React", "Node"];
            const list = wrapper.querySelector(".ex5-list");
    
            const markup = technologies
              .map(function (technology) {
                return '<li class="ex5-list-item">' + technology + "</li>";
              })
              .join("");
    
            console.log(markup);
            list.innerHTML = markup;
          })();
        </script>
      </div>
    </div>

    Conclusion: This example demonstrates generating HTML from an array with JavaScript. It shows how map(), join(), and innerHTML can be combined to build a list dynamically.

    Example 6. Add HTML with innerHTML plus equals

    Article title

    <div class="ex6-article-example">
      <div>
        <article class="ex6-article">
          <h2>Article title</h2>
        </article>
    
        <style>
          .ex6-article-example {
            padding: 16px;
          }
    
          .ex6-article-example .ex6-article {
            max-width: 320px;
          }
    
          .ex6-article-example .ex6-article-text {
            color: tomato;
          }
        </style>
    
        <script>
          (function () {
            const wrapper = document.currentScript.closest(".ex6-article-example");
            const article = wrapper.querySelector(".ex6-article");
            const htmlString =
              '<p class="ex6-article-text">Nullam quis ante. Vestibulum dapibus nunc ac augue. In consectetuer turpis ut velit.</p>' +
              '<a class="ex6-link" href="https://nikitagoluban.eu">Read more...</a>';
    
            article.innerHTML += htmlString;
          })();
        </script>
      </div>
    </div>

    Conclusion: This example shows how to add new HTML to existing content with innerHTML +=. It demonstrates extending an article by inserting a paragraph and a link.

    Example 7. Insert HTML at exact positions

    • HTML
    • CSS
    • JavaScript
    <div class="ex7-list-example">
      <div>
        <ul class="ex7-list">
          <li class="ex7-list-item">HTML</li>
          <li class="ex7-list-item">CSS</li>
          <li class="ex7-list-item">JavaScript</li>
        </ul>
    
        <style>
          .ex7-list-example {
            padding: 16px;
          }
    
          .ex7-list-example .ex7-list {
            padding: 0;
            margin: 0;
            list-style-type: none;
          }
    
          .ex7-list-example .ex7-list-item {
            display: flex;
            align-items: center;
            padding: 8px;
            border-width: 2px;
            border-style: dashed;
          }
    
          .ex7-list-example .ex7-list-item.ex7-new::before {
            content: "";
            width: 12px;
            height: 12px;
            margin-right: 8px;
            border-radius: 50%;
            background-color: green;
          }
    
          .ex7-list-example .ex7-list-item:nth-child(even) {
            border-color: tomato;
          }
    
          .ex7-list-example .ex7-list-item:nth-child(odd) {
            border-color: blueviolet;
          }
    
          .ex7-list-example .ex7-list-item:not(:last-child) {
            margin-bottom: 8px;
          }
        </style>
    
        <script>
          (function () {
            const wrapper = document.currentScript.closest(".ex7-list-example");
            const list = wrapper.querySelector(".ex7-list");
    
            const newTechnologies = ["React", "TypeScript", "Node.js"];
            const markup = newTechnologies
              .map(function (technology) {
                return '<li class="ex7-list-item ex7-new">' + technology + "</li>";
              })
              .join("");
    
            list.insertAdjacentHTML("beforeend", markup);
            list.insertAdjacentHTML("beforebegin", "<h2>Popular technologies</h2>");
          })();
        </script>
      </div>
    </div>

    Conclusion: This example demonstrates insertAdjacentHTML(). It shows how new HTML can be inserted in different positions relative to an existing element, both before the list and inside it.

    ← Back