Welcome to the Introduction to DOM Manipulation!
In web development, DOM manipulation refers to the process of changing and updating the HTML structure and content dynamically using JavaScript. The DOM (Document Object Model) represents the web page as a tree-like structure, where each element is a node with properties and methods.
DOM manipulation is important for several reasons:
Interactivity: With DOM manipulation, you can respond to user actions and create dynamic and interactive user interfaces. For example, you can change the content of an element based on user input or show and hide elements based on certain conditions.
Data Binding: By manipulating the DOM, you can bind data to HTML elements, allowing the web page to display and update real-time data. This is commonly used in web applications where data needs to be fetched from an API or updated continuously.
Dynamic Content: DOM manipulation enables you to dynamically generate HTML elements and insert them into the web page. This is useful for creating content on the fly, such as adding new items to a shopping cart or displaying a list of user-generated comments.
Now, let's see some examples of DOM manipulation in JavaScript:
1// Let's start by selecting an HTML element
2const heading = document.querySelector('h1');
3
4// We can modify the text content of the element
5heading.textContent = 'Hello, World!';
6
7// We can also change the style of the element
8heading.style.color = 'blue';
9
10// Creating a new element
11const paragraph = document.createElement('p');
12paragraph.textContent = 'This is a dynamically created paragraph.';
13
14// Appending the new element to the DOM
15
16document.body.appendChild(paragraph);
In this example, we start by selecting the h1
element using document.querySelector()
. We then change the text content of the element to 'Hello, World!' using the textContent
property. Next, we change the style of the element by modifying the color
property of the style
object. Finally, we create a new p
element, set its text content, and append it to the body
element using appendChild()
.
DOM manipulation opens up a world of possibilities for creating dynamic and interactive web pages. In the upcoming sections, we'll dive deeper into selecting elements, modifying their properties, creating new elements, and handling user events.
xxxxxxxxxx
// Let's start by selecting an HTML element
const heading = document.querySelector('h1');
// We can modify the text content of the element
heading.textContent = 'Hello, World!';
// We can also change the style of the element
heading.style.color = 'blue';
// Creating a new element
const paragraph = document.createElement('p');
paragraph.textContent = 'This is a dynamically created paragraph.';
// Appending the new element to the DOM
document.body.appendChild(paragraph);