JavaScript DOM Elements

Create, insert and remove elements.

✍️ 3 exercises + code challenge in this lesson

You can build new parts of the page with JavaScript:

  • document.createElement("li"): create an element.
  • parent.append(child) / prepend(): insert it.
  • element.remove(): delete it.
  • element.insertAdjacentHTML("beforeend", html): insert an HTML string.
When adding text from users, use textContent, not innerHTML. It prevents malicious HTML from being injected (XSS).

Key Takeaways: JavaScript DOM Elements

Mastering JavaScript DOM Elements helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript DOM Elements Code Example

JavaScript
<input id="item" placeholder="New item">
<button id="add">Add</button>
<ul id="list"></ul>

<script>
  const list = document.getElementById("list");

  document.getElementById("add").addEventListener("click", () => {
    const input = document.getElementById("item");
    if (!input.value.trim()) return;

    const li = document.createElement("li");
    li.textContent = input.value + " ";

    const remove = document.createElement("button");
    remove.textContent = "✕";
    remove.onclick = () => li.remove();

    li.append(remove);
    list.append(li);
    input.value = "";
    input.focus();
  });
</script>
Free sign-in required · Google login available

JavaScript DOM Elements Practice Exercises

Check what you learned in “JavaScript DOM Elements”.

/ 3 solved
Fill in the blank

Create a new <li> element.

const li = document.("li");
✓ Correct! Not quite. Try again.
Multiple choice

Which property safely inserts user text without interpreting HTML?

✓ Correct! Not quite. Try again.
Code challenge

Create three <li> items (One, Two, Three) and append them to the <ul id="list">.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services