DOM Manipulation: Selecting and Manipulating DOM Elements
Introduction to the DOM
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.
Selecting Elements
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:
1. Selecting an Element by ID
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.
2. Selecting Elements by Class Name
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.
3. Selecting Elements Using a CSS Selector
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.
Manipulating Elements
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.
1. Changing Text Content
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!".
2. Changing an Attribute
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.
3. Changing Styles
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.
Creating and Removing Elements
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.
1. Creating a New Element
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.2. Removing an 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.
Real-World Example: To-Do List
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.
HTML Structure
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:
- We have a heading (
) with an ID of heading.
- An unordered list (
- ) with an ID of todo-list, where our to-do items will be displayed.
- An input field for adding new to-do items, with an ID of new-todo.
- A button with an ID of add-todo to add new items to the list.
JavaScript for Interactivity
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>
Explanation:
- Selecting Elements: We begin by selecting the necessary elements using their IDs.
- Event Listener: We add a click event listener to the "Add To-Do" button. When clicked, the event listener function is triggered.
- Input Validation: Inside the function, we first check if the input field is empty to prevent adding empty to-do items.
- Creating a New Element: If the input is not empty, we create a new
- element and set its text content to the value entered in the input field.
- Appending the New Item: The new
- is then appended to the existing
- element.
- Clearing the Input Field: Finally, the input field is cleared, ready for the next to-do item.
This simple application demonstrates the power of DOM manipulation in creating interactive and dynamic web pages.
Conclusion
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
