JavaScript DOM

Select and change HTML elements.

✍️ 3 exercises + code challenge in this lesson

The DOM (Document Object Model) is the browser's tree of objects representing the page. JavaScript uses it to read and change anything on the page.

Finding elements

  • document.getElementById("id")
  • document.querySelector(".card"): the first match of a CSS selector
  • document.querySelectorAll("li"): all matches

Changing elements

  • textContent / innerHTML: content
  • style.color: inline styles
  • classList.add(), remove(), toggle(): classes
  • setAttribute(), getAttribute(): attributes

Key Takeaways: JavaScript DOM

Mastering JavaScript DOM 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 Code Example

JavaScript
<style> .done { text-decoration: line-through; color: #94A3B8; } </style>

<h2 id="title">My tasks</h2>
<ul>
  <li>Learn HTML</li>
  <li>Learn CSS</li>
  <li>Learn JavaScript</li>
</ul>
<button onclick="update()">Update with DOM</button>

<script>
  function update() {
    document.getElementById("title").textContent = "Tasks (updated)";
    document.querySelector("h2").style.color = "#2563EB";
    document.querySelectorAll("li").forEach((li, i) => {
      if (i < 2) li.classList.add("done");
    });
  }
</script>
Free sign-in required · Google login available

JavaScript DOM Practice Exercises

Check what you learned in “JavaScript DOM”.

/ 3 solved
Fill in the blank

Select the first element with the class "card".

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

Which property adds or removes a CSS class?

✓ Correct! Not quite. Try again.
Code challenge

Add the class "active" to the element with id "box".

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