Home >Web Front-end >JS Tutorial >DOM Manipulation: Selecting and Manipulating DOM Elements
The Document Object Model (DOM) is a crucial concept for web development. It serves as a programming interface that allows developers to interact with and modify the structure, style, and content of a web page. When a web page is loaded in the browser, the HTML document is converted into the DOM, a tree-like structure where each node represents an element, attribute, or text. This structure enables developers to access and manipulate parts of the page dynamically, making the web experience more interactive and engaging.
For beginners and those unfamiliar with the DOM, think of it as the blueprint of a house. Just as you can rearrange furniture or paint walls in a house, the DOM lets you change the content and style of a web page after it has loaded.
Before you can manipulate the DOM, you need to select the elements you wish to work with. JavaScript provides several methods for selecting elements, allowing you to interact with different parts of the web page. Here's a look at some common methods:
The getElementById method is one of the most straightforward ways to select a single element. It returns the element that matches the specified ID.
// Selecting an element by ID const heading = document.getElementById('heading');
In this example, heading will now reference the element with the ID of heading. You can use this reference to manipulate the element further.
To select multiple elements with the same class, you can use the getElementsByClassName method. This method returns a live HTMLCollection of elements.
// Selecting elements by class name const items = document.getElementsByClassName('item');
The items variable will now hold a collection of all elements with the class name item. This method is particularly useful when you need to apply the same action to multiple elements.
The querySelector and querySelectorAll methods allow you to select elements using CSS selectors. These methods are versatile and can be used to target elements by tag name, class, ID, or any other valid CSS selector.
// Selecting a single element using a CSS selector const button = document.querySelector('button'); // Selecting multiple elements using a CSS selector const listItems = document.querySelectorAll('li');
querySelector selects the first element that matches the selector, while querySelectorAll selects all matching elements and returns a NodeList, which is similar to an array.
Once you've selected an element, you can manipulate it to change its content, attributes, and styles. This allows you to create dynamic web pages that respond to user interactions or other events.
The textContent property allows you to change the text within an element. This is useful for updating the content dynamically based on user input or other conditions.
// Changing text content heading.textContent = 'Hello, World!';
In this example, the text inside the element referenced by heading will be updated to "Hello, World!".
The setAttribute method allows you to modify an element's attributes, such as src, href, alt, or disabled.
// Changing an attribute button.setAttribute('disabled', true);
Here, the button is disabled by setting the disabled attribute to true. This can be used to prevent user interaction until a certain condition is met.
The style property allows you to modify the inline CSS styles of an element. You can change properties like color, backgroundColor, fontSize, and more.
// Changing styles heading.style.color = 'blue';
In this example, the color of the text within the heading element is changed to blue.
In addition to modifying existing elements, you can create new elements and add them to the DOM, or remove elements that are no longer needed.
You can create a new element using the createElement method. Once created, you can set its properties and append it to an existing element in the DOM.
// Creating a new element const newElement = document.createElement('p'); newElement.textContent = 'This is a new paragraph.'; document.body.appendChild(newElement);
In this example, a new
element is created, its text content is set, and it is added to the end of the
element.To remove an element from the DOM, you can use the remove method. This is particularly useful for dynamically managing the content on your page.
// Removing an element const oldElement = document.getElementById('old-element'); oldElement.remove();
Here, the element with the ID old-element is removed from the DOM, effectively deleting it from the web page.
To see these concepts in action, let's build a simple To-Do List application. This example will demonstrate how to select and manipulate DOM elements in a real-world scenario.
First, let's create the HTML structure for our To-Do List.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>To-Do List</title> </head> <body> <h1 id="heading">To-Do List</h1> <ul id="todo-list"></ul> <input type="text" id="new-todo" placeholder="New to-do"> <button id="add-todo">Add To-Do</button> </body> </html>
In this structure:
Next, we'll add some JavaScript to make the To-Do List interactive.
<script> // Selecting elements const todoList = document.getElementById('todo-list'); const newTodoInput = document.getElementById('new-todo'); const addTodoButton = document.getElementById('add-todo'); // Adding a new to-do item addTodoButton.addEventListener('click', () => { const newTodoText = newTodoInput.value; if (newTodoText === '') return; // Prevent adding empty to-do items // Create a new list item const newTodoItem = document.createElement('li'); newTodoItem.textContent = newTodoText; // Append the new item to the list todoList.appendChild(newTodoItem); // Clear the input field newTodoInput.value = ''; }); </script>
This simple application demonstrates the power of DOM manipulation in creating interactive and dynamic web pages.
DOM manipulation is a fundamental skill for any web developer. By understanding how to select and manipulate DOM elements, you can create web pages that are not only static but also responsive to user interactions. The examples provided in this article serve as a foundation for more advanced topics, such as event handling, animations, and dynamic content loading.
By practicing these techniques and applying them to real-world scenarios, you'll gain a deeper understanding of how the web works and be well on your way to mastering front-end development.
The above is the detailed content of DOM Manipulation: Selecting and Manipulating DOM Elements. For more information, please follow other related articles on the PHP Chinese website!