Home Web Front-end JS Tutorial DOM Manipulation from Simple Updates to Virtual DOM

DOM Manipulation from Simple Updates to Virtual DOM

Jan 09, 2025 am 06:39 AM

TLDR

Introduction

When building web applications, one of the most fundamental challenges developers face is efficiently updating the Document Object Model (DOM) in response to user interactions and state changes. Let's explore this concept by examining three different implementations of a todo application, each showcasing a different approach to DOM manipulation.

DOM Manipulation from Simple Updates to Virtual DOM

Github: https://github.com/sreeharsha-rav/javascript_projects/blob/main/todo-app/README.md

The Evolution of DOM Updates

1. Direct DOM Manipulation: The Simple Approach

In our first implementation, we used the most straightforward approach: directly manipulating the DOM whenever a change occurred. Here's a simplified version of how we handled adding a new todo:

function addTodo() {
    const todoText = input.value;
    const todoElement = document.createElement('div');
    todoElement.textContent = todoText;
    todoList.appendChild(todoElement);
}
Copy after login

This approach is intuitive and works well for simple applications, but it has limitations:

  • Each operation directly touches the DOM
  • No central place to track the application's state
  • Difficult to maintain consistency across multiple updates
  • Can become inefficient with frequent updates

2. State-Based DOM Manipulation: Adding Structure

Our second implementation introduced the concept of state management. Instead of directly manipulating the DOM, we maintained a central state and updated the DOM based on that state:

const todoStore = new Map();

function addTodo(text) {
    // Update state
    const id = nextId++;
    todoStore.set(id, {
        text,
        completed: false
    });

    // Update DOM
    const todoElement = createTodoElement(text, id);
    todoList.appendChild(todoElement);
}
Copy after login

This approach brought several improvements:

  • Clear separation between data (state) and presentation (DOM)
  • More predictable application behavior
  • Easier to implement features like undo/redo
  • Better organization of code

However, we still faced a challenge: ensuring our DOM updates were efficient and maintaining consistency between our state and the UI.

3. Virtual DOM-like Approach: Smart Updates

Our final implementation introduced a simple virtual DOM-like mechanism using state diffing. This approach represents a significant leap in sophistication:

let todoState = [];      // Current state
let oldTodoState = [];   // Previous state

function updateState(newTodos) {
    // Find what changed
    const added = newTodos.filter(newTodo => 
        !oldTodoState.some(oldTodo => oldTodo.id === newTodo.id)
    );
    const deleted = oldTodoState.filter(oldTodo => 
        !newTodos.some(newTodo => newTodo.id === oldTodo.id)
    );
    const updated = // ... find updated items

    // Update only what changed
    added.forEach(todo => addTodoElement(todo));
    deleted.forEach(todo => removeTodoElement(todo));
    updated.forEach(todo => updateTodoElement(todo));

    // Save current state for next comparison
    oldTodoState = [...newTodos];
}
Copy after login

Understanding Reconciliation and Diffing

The concept of reconciliation, popularized by React, is about efficiently updating the DOM to match our desired state. Our simple implementation demonstrates three key aspects:

1. State Comparison

We maintain two versions of our state: current and previous. This allows us to detect exactly what changed between updates. The process of finding these differences is called "diffing."

2. Minimal Updates

Instead of rebuilding everything, we only update what changed:

  • New items are added to the DOM
  • Removed items are deleted from the DOM
  • Modified items are updated in place

3. Batch Processing

All our DOM updates happen in a single pass, after we've calculated all the differences. This is more efficient than making updates one at a time as changes occur.

The Benefits of Smart DOM Manipulation

As we progressed through these implementations, we gained several advantages:

  1. Performance: By only updating what changed, we minimize expensive DOM operations.
  2. Predictability: With a single source of truth (our state), it's easier to understand and debug our application.
  3. Scalability: The diffing approach remains efficient even as our application grows.
  4. Maintainability: Clear separation of concerns makes our code easier to understand and modify.

Real-World Implications

While our implementation is simplified, it demonstrates the core concepts behind modern frontend frameworks like React. The actual Virtual DOM implementation in React is more sophisticated, handling:

  • Complex nested structures
  • Event delegation
  • Component lifecycle
  • Batched updates
  • Cross-browser compatibility

Conclusion

The evolution of our todo application shows how different approaches to DOM manipulation come with different trade-offs. While direct manipulation is simpler to understand and implement, a more structured approach with state management and smart updates leads to more maintainable and scalable applications.

The concepts of reconciliation and diffing, even in their simplified form, demonstrate why modern frameworks like React are so powerful. They handle these complex updates automatically, allowing developers to focus on building features rather than optimizing DOM updates.

As web applications become more complex, understanding these fundamental concepts becomes increasingly important. Whether you're using a framework or building something from scratch, knowing how and why DOM updates work the way they do will make you a more effective developer.

The above is the detailed content of DOM Manipulation from Simple Updates to Virtual DOM. 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
1268
29
C# Tutorial
1246
24
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.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles