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

DOM Manipulation: Selecting and Manipulating DOM Elements

PHPz
PHPzOriginal
2024-08-09 12:34:321021browse

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:

    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:
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