The DOM (Document Object Model) is the interface that allows JavaScript to interact with and manipulate the structure, content, and style of a web page. When a web page is loaded in a browser, the browser converts the HTML and CSS into the DOM, enabling JavaScript to make dynamic changes to the page.
getElementById:
let header = document.getElementById('header');
querySelector:
let paragraph = document.querySelector('p');
let title = document.getElementById('title');
title.textContent = 'Updated Title';
let button = document.querySelector('button');
button.style.backgroundColor = 'blue';
The DOM allows web pages to be:
Here’s a complete example of how to manipulate the DOM in JavaScript, showcasing some of the most common techniques such as selecting elements, modifying their content, changing styles, and responding to user interactions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Example</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
}
#dynamic-text {
font-size: 1.5rem;
color: blue;
margin: 20px 0;
}
.color-box {
width: 100px;
height: 100px;
margin: 10px auto;
background-color: lightgray;
border: 1px solid #ccc;
}
button {
padding: 10px 20px;
font-size: 1rem;
}
</style>
</head>
<body>
<h1>DOM Manipulation Example</h1>
<p id="dynamic-text">Click the button to change this text.</p>
<div class="color-box"></div>
<button id="change-btn">Change Text & Color</button>
<script src="script.js"></script>
</body>
</html>
// Select elements
const textElement = document.getElementById('dynamic-text');
const colorBox = document.querySelector('.color-box');
const changeButton = document.getElementById('change-btn');
// Add an event listener to the button
changeButton.addEventListener('click', () => {
// Change the text content of the paragraph
textElement.textContent = 'The text has been updated!';
// Change the text color
textElement.style.color = 'green';
// Update the background color of the box
const randomColor = getRandomColor();
colorBox.style.backgroundColor = randomColor;
// Add a border to the box
colorBox.style.border = '3px solid black';
});
// Helper function to generate a random color
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
#change-btn) is selected using getElementById.#dynamic-text) is updated using textContent, and its color is changed using style.color..color-box div is updated to a random color generated by the getRandomColor function..color-box, like adding a thicker border..color-box background to a random color.This example demonstrates the basics of DOM manipulation, styling, and interaction.