DOM Manipulation
⚡ JavaScriptChange HTML content, styles, and respond to user events.
0/4 completed
DOM Manipulation
The DOM (Document Object Model) lets JavaScript interact with HTML elements.
Selecting Elements
document.getElementById("myId");
document.querySelector(".myClass");
document.querySelectorAll("p");Changing Content
element.textContent = "New text";
element.innerHTML = "<strong>Bold text</strong>";Changing Styles
element.style.color = "red";
element.style.backgroundColor = "#f0f0f0";Event Listeners
button.addEventListener("click", function() {
alert("Button clicked!");
});
Example
<!DOCTYPE html>
<html>
<head>
<style>
.container { text-align: center; padding: 40px; font-family: Arial; }
.box {
width: 200px; height: 200px; margin: 20px auto;
background: #5E256D; border-radius: 16px;
display: flex; align-items: center; justify-content: center;
color: white; font-size: 1.2rem; font-weight: bold;
transition: all 0.3s;
}
button {
padding: 12px 24px; margin: 8px;
border: none; border-radius: 8px; cursor: pointer;
font-size: 1rem; font-weight: 600;
}
.btn-red { background: #ef4444; color: white; }
.btn-blue { background: #3b82f6; color: white; }
.btn-green { background: #10b981; color: white; }
</style>
</head>
<body>
<div class="container">
<div class="box" id="myBox">Click a button!</div>
<button class="btn-red" onclick="changeColor('#ef4444', 'Red!')">Red</button>
<button class="btn-blue" onclick="changeColor('#3b82f6', 'Blue!')">Blue</button>
<button class="btn-green" onclick="changeColor('#10b981', 'Green!')">Green</button>
</div>
<script>
function changeColor(color, text) {
let box = document.getElementById("myBox");
box.style.backgroundColor = color;
box.textContent = text;
}
</script>
</body>
</html>
Exercises
Exercise 1. Update an Element
Medium
Get the element with id "title" and set its text to "Done!"
Use exactly: document.getElementById("title").textContent = "Done!";
Use exactly: document.getElementById("title").textContent = "Done!";
// your code here
Expected Output
The title element now shows "Done!".