⚡
DOM Manipulation
Intermediate
100 XP
40 min
Lesson Content
DOM Manipulation
The Document Object Model (DOM) represents your HTML page as a tree of objects. JavaScript can access and modify these objects to create dynamic, interactive web pages.
Selecting Elements
// By ID
let element = document.getElementById('myId');
// By class
let elements = document.getElementsByClassName('myClass');
// By tag
let divs = document.getElementsByTagName('div');
// Modern selectors
let el = document.querySelector('#myId');
let all = document.querySelectorAll('.myClass');Modifying Content
// Change text
element.textContent = 'New text';
element.innerHTML = 'Bold text';
// Change attributes
element.setAttribute('class', 'new-class');
element.style.color = 'red';
// Add/remove classes
element.classList.add('active');
element.classList.remove('inactive');Creating Elements
let newDiv = document.createElement('div');
newDiv.textContent = 'New element';
document.body.appendChild(newDiv);Example Code
Select and modify HTML elements
<!DOCTYPE html>
<html><head><title>DOM Practice</title></head><body>
<h1 id="title">Original Title</h1>
<p class="text">Original text</p>
<div id="container"></div>
<script>
// Change title text
document.getElementById('title').textContent = 'New Title';
// Change paragraph
document.querySelector('.text').textContent = 'Updated text';
// Create new element
let newDiv = document.createElement('div');
newDiv.textContent = 'New element created!';
newDiv.style.color = 'blue';
document.getElementById('container').appendChild(newDiv);
</script>
</body></html>Expected Output:
New Title
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code