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.
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); }
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); }
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]; }
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:
- Performance: By only updating what changed, we minimize expensive DOM operations.
- Predictability: With a single source of truth (our state), it's easier to understand and debug our application.
- Scalability: The diffing approach remains efficient even as our application grows.
- 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!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
