Home Web Front-end JS Tutorial DOM Manipulation: Selecting and Manipulating DOM Elements

DOM Manipulation: Selecting and Manipulating DOM Elements

Aug 09, 2024 pm 12:34 PM

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');
Copy after login

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');
Copy after login

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');
Copy after login

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!';
Copy after login

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);
Copy after login

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';
Copy after login

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);
Copy after login

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();
Copy after login

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>
Copy after login

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>
    
    Copy after login

    Explanation:

    1. Selecting Elements: We begin by selecting the necessary elements using their IDs.
    2. Event Listener: We add a click event listener to the "Add To-Do" button. When clicked, the event listener function is triggered.
    3. Input Validation: Inside the function, we first check if the input field is empty to prevent adding empty to-do items.
    4. Creating a New Element: If the input is not empty, we create a new
    5. element and set its text content to the value entered in the input field.
    6. Appending the New Item: The new
    7. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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 Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

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.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

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.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

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

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

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

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

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.

See all articles