agyanadda@gmail.com

JS DOM

Working with the Page 1 min read Updated Dec 1, 2026 Topic 25 of 38

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

Select elements

Method Returns
document.getElementById('id') one element
document.querySelector('.card') the first match (any CSS selector)
document.querySelectorAll('li') all matches (a list)

Change elements

  • Text: el.textContent = 'New text';
  • HTML: el.innerHTML = '<b>Bold</b>';
  • Style: el.style.color = 'red';
  • Classes: el.classList.add('active'), remove, toggle
  • Attributes: img.src = 'new.jpg';, el.setAttribute('title', 'Hi')

Changing classes is usually better than setting many inline styles — keep the design in CSS.

Example

Example — Select and change elements HTML
<style>
  .highlight { background: #fff3cd; font-weight: bold; }
</style>

<h2 id="title">DOM Demo</h2>
<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
<button onclick="change()">Change page</button>

<script>
  function change() {
    document.getElementById('title').textContent = 'Changed with the DOM!';
    document.querySelector('h2').style.color = '#1f386b';
    document.querySelectorAll('li').forEach(li => li.classList.toggle('highlight'));
  }
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method returns all elements matching a CSS selector?

Exercise 2 True / False

classList.toggle adds a class if it is missing and removes it if present.

Exercise 3 Fill in the Blank

DOM stands for Document Object ___.

Frequently Asked Questions

The script ran before the element existed. Put the script at the end of body or use the defer attribute.