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>