掌握JavaScript核心技巧 轻松实现DOM元素的增删改查与实战应用解析

引言:DOM操作的重要性
在现代Web开发中,文档对象模型(DOM)操作是JavaScript最基础也是最重要的技能之一。无论是构建动态的用户界面,还是处理复杂的交互逻辑,DOM的增删改查操作都是不可或缺的。本文将深入解析DOM操作的核心技巧,通过详细的代码示例和实战应用,帮助你全面掌握这一关键技能。
一、DOM查询:精准定位元素
1.1 基础查询方法
DOM查询是所有操作的基础。JavaScript提供了多种方法来获取DOM元素,每种方法都有其特定的使用场景。
getElementById()
这是最常用且性能最好的查询方法,通过元素的ID直接获取单个元素。
// HTML结构
//

const headerElement = document.getElementById(‘header’);
console.log(headerElement); // 输出:

// 实际应用:修改元素内容
headerElement.textContent = ‘新的头部内容’;
headerElement.style.color = ‘blue’;
getElementsByClassName()
通过类名获取元素集合,返回的是HTMLCollection(动态集合)。
// HTML结构
//

项目1

//

项目2

//

项目3

const items = document.getElementsByClassName(‘item’);
console.log(items.length); // 输出: 3

// 遍历所有元素并修改
for (let i = 0; i < items.length; i++) { items[i].style.backgroundColor = '#f0f0f0'; items[i].textContent = `修改后的项目${i + 1}`; } getElementsByTagName() 通过标签名获取元素集合,同样返回HTMLCollection。 // 获取所有段落元素 const paragraphs = document.getElementsByTagName('p'); console.log(paragraphs.length); // 输出: 2 // 修改所有段落的字体大小 for (let p of paragraphs) { p.style.fontSize = '16px'; p.style.lineHeight = '1.6'; } 1.2 现代查询方法:querySelector和querySelectorAll querySelector() 使用CSS选择器语法获取第一个匹配的元素,返回单个元素。 // HTML结构 //

//

主标题

//

内容段落

//

// 获取第一个匹配的元素
const firstTitle = document.querySelector(‘.title’);
console.log(firstTitle.textContent); // 输出: 主标题

// 复杂选择器示例
const specificElement = document.querySelector(‘.container > p.content’);
console.log(specificElement.textContent); // 输出: 内容段落

// 实际应用:表单验证
const emailInput = document.querySelector(‘input[type=”email”]’);
if (emailInput) {
emailInput.addEventListener(‘blur’, function() {
if (!this.value.includes(‘@’)) {
this.style.borderColor = ‘red’;
alert(‘请输入有效的邮箱地址’);
}
});
}
querySelectorAll()
使用CSS选择器语法获取所有匹配的元素,返回NodeList(静态集合)。
// HTML结构
//

    //

  • 用户A
  • //

  • 用户B
  • //

  • 用户C
  • //

// 获取所有匹配的元素
const users = document.querySelectorAll(‘.user-list li[data-id]’);
console.log(users.length); // 输出: 3

// NodeList支持forEach方法
users.forEach((user, index) => {
user.textContent = `用户${String.fromCharCode(65 + index)}`;
user.style.padding = ‘5px’;
user.style.borderBottom = ‘1px solid #ccc’;
});

// 实际应用:批量操作
const buttons = document.querySelectorAll(‘button[data-action]’);
buttons.forEach(button => {
button.addEventListener(‘click’, function() {
const action = this.dataset.action;
console.log(`执行操作: ${action}`);
// 根据不同的action执行不同的逻辑
switch(action) {
case ‘save’:
saveData();
break;
case ‘delete’:
deleteData();
break;
}
});
});
1.3 高级查询技巧
遍历DOM树
// 获取父元素
const child = document.getElementById(‘child’);
const parent = child.parentElement; // 获取直接父元素
const ancestors = []; // 获取所有祖先元素
let current = child.parentElement;
while (current) {
ancestors.push(current);
current = current.parentElement;
}
console.log(ancestors); // 输出所有祖先元素

// 获取子元素
const container = document.getElementById(‘container’);
const firstChild = container.firstChild; // 第一个子节点(包括文本节点)
const firstElementChild = container.firstElementChild; // 第一个元素子节点
const children = container.children; // 所有元素子节点(HTMLCollection)
const childNodes = container.childNodes; // 所有子节点(NodeList)

// 兄弟元素
const nextSibling = child.nextSibling; // 下一个兄弟节点
const nextElementSibling = child.nextElementSibling; // 下一个兄弟元素
const previousSibling = child.previousSibling; // 上一个兄弟节点
const previousElementSibling = child.previousElementSibling; // 上一个兄弟元素
自定义数据属性查询
// HTML结构
//

用户信息

const userDiv = document.querySelector(‘div[data-user-id]’);
const userId = userDiv.dataset.userId; // “123”
const role = userDiv.dataset.role; // “admin”
const status = userDiv.dataset.status; // “active”

// 动态查询特定数据的元素
const activeUsers = document.querySelectorAll(‘[data-status=”active”]’);
activeUsers.forEach(user => {
user.style.color = ‘green’;
user.style.fontWeight = ‘bold’;
});
二、DOM创建与插入:动态构建页面
2.1 创建元素
createElement()
// 创建基本元素
const newDiv = document.createElement(‘div’);
newDiv.className = ‘alert alert-success’;
newDiv.textContent = ‘操作成功!’;
newDiv.style.padding = ’10px’;
newDiv.style.margin = ’10px 0′;
newDiv.style.backgroundColor = ‘#d4edda’;
newDiv.style.border = ‘1px solid #c3e6cb’;
newDiv.style.borderRadius = ‘4px’;

// 创建带属性的元素
const link = document.createElement(‘a’);
link.href = ‘https://example.com’;
link.target = ‘_blank’;
link.textContent = ‘访问示例网站’;
link.style.color = ‘#007bff’;
link.style.textDecoration = ‘none’;

// 创建复杂结构
function createCard(title, content, footer) {
const card = document.createElement(‘div’);
card.className = ‘card’;
card.style.border = ‘1px solid #ddd’;
card.style.borderRadius = ‘8px’;
card.style.padding = ’16px’;
card.style.margin = ’10px 0′;
card.style.boxShadow = ‘0 2px 4px rgba(0,0,0,0.1)’;

const cardTitle = document.createElement(‘h3’);
cardTitle.textContent = title;
cardTitle.style.marginTop = ‘0’;
cardTitle.style.color = ‘#333’;

const cardContent = document.createElement(‘p’);
cardContent.textContent = content;
cardContent.style.color = ‘#666’;
cardContent.style.lineHeight = ‘1.5’;

const cardFooter = document.createElement(‘div’);
cardFooter.textContent = footer;
cardFooter.style.marginTop = ’10px’;
cardFooter.style.fontSize = ’12px’;
cardFooter.style.color = ‘#999’;
cardFooter.style.borderTop = ‘1px solid #eee’;
cardFooter.style.paddingTop = ‘8px’;

card.appendChild(cardTitle);
card.appendChild(cardContent);
card.appendChild(cardFooter);

return card;
}

// 使用示例
const myCard = createCard(‘欢迎’, ‘这是一个动态创建的卡片组件’, ‘创建时间: 2024’);
document.body.appendChild(myCard);
createDocumentFragment()
对于需要插入多个元素的情况,使用DocumentFragment可以减少回流和重绘。
// 创建文档片段
const fragment = document.createDocumentFragment();

// 批量创建元素
for (let i = 1; i <= 100; i++) { const item = document.createElement('div'); item.className = 'list-item'; item.textContent = `列表项 ${i}`; item.style.padding = '8px'; item.style.borderBottom = '1px solid #eee'; // 将元素添加到片段中(不会触发重绘) fragment.appendChild(item); } // 一次性插入到DOM中 const container = document.getElementById('list-container'); container.appendChild(fragment); // 只触发一次重绘 2.2 插入元素 appendChild() 在父元素的末尾插入元素。 // HTML结构 //

// 已有内容
//

const parent = document.getElementById(‘parent’);
const newElement = document.createElement(‘div’);
newElement.textContent = ‘新添加的元素’;
newElement.style.color = ‘red’;

// 插入到末尾
parent.appendChild(newElement);
// 结果:

已有内容

新添加的元素

insertBefore()
在指定元素之前插入元素。
// HTML结构
//

// 在之前的元素
// 在之后的元素
//

const parent = document.getElementById(‘parent’);
const referenceElement = document.getElementById(‘beforeMe’);
const newElement = document.createElement(‘span’);
newElement.textContent = ‘插入的新元素’;
newElement.style.color = ‘blue’;

// 在referenceElement之前插入
parent.insertBefore(newElement, referenceElement);
// 结果:

插入的新元素在之前的元素在之后的元素

insertAdjacentHTML()
在指定位置插入HTML字符串,性能较好。
// HTML结构
//

//

已有内容

//

const container = document.getElementById(‘container’);

// 在元素内部的开头插入
container.insertAdjacentHTML(‘afterbegin’, ‘

开头插入的内容

‘);

// 在元素内部的结尾插入
container.insertAdjacentHTML(‘beforeend’, ‘

结尾插入的内容

‘);

// 在元素之前插入
container.insertAdjacentHTML(‘beforebegin’, ‘

之前插入的内容

‘);

// 在元素之后插入
container.insertAdjacentHTML(‘afterend’, ‘

之后插入的内容

‘);
replaceChild()
替换元素。
// HTML结构
//

// 旧元素
//

const parent = document.getElementById(‘parent’);
const oldElement = document.getElementById(‘1’);
const newElement = document.createElement(‘span’);
newElement.textContent = ‘新元素’;
newElement.style.color = ‘green’;

// 替换元素
parent.replaceChild(newElement, oldElement);
// 结果:

新元素

2.3 实战应用:动态列表管理
// 完整的列表管理类
class DynamicListManager {
constructor(containerId) {
this.container = document.getElementById(containerId);
this.items = [];
}

// 添加项目
addItem(text, color = ‘#333’) {
const item = document.createElement(‘div’);
item.className = ‘list-item’;
item.textContent = text;
item.style.padding = ’10px’;
item.style.margin = ‘5px 0’;
item.style.borderLeft = `4px solid ${color}`;
item.style.backgroundColor = ‘#f8f9fa’;
item.style.borderRadius = ‘4px’;
item.style.display = ‘flex’;
item.style.justifyContent = ‘space-between’;
item.style.alignItems = ‘center’;

// 添加删除按钮
const deleteBtn = document.createElement(‘button’);
deleteBtn.textContent = ‘删除’;
deleteBtn.style.padding = ‘4px 8px’;
deleteBtn.style.backgroundColor = ‘#dc3545’;
deleteBtn.style.color = ‘white’;
deleteBtn.style.border = ‘none’;
deleteBtn.style.borderRadius = ‘3px’;
deleteBtn.style.cursor = ‘pointer’;
deleteBtn.onclick = () => this.removeItem(item);

item.appendChild(deleteBtn);
this.container.appendChild(item);
this.items.push({ element: item, text, color });

return item;
}

// 删除项目
removeItem(itemElement) {
// 添加删除动画
itemElement.style.transition = ‘all 0.3s ease’;
itemElement.style.opacity = ‘0’;
itemElement.style.transform = ‘translateX(-20px)’;

setTimeout(() => {
this.container.removeChild(itemElement);
this.items = this.items.filter(item => item.element !== itemElement);
}, 300);
}

// 批量添加
addBatch(items) {
const fragment = document.createDocumentFragment();
items.forEach(({ text, color }) => {
const item = document.createElement(‘div’);
item.className = ‘list-item’;
item.textContent = text;
item.style.padding = ’10px’;
item.style.margin = ‘5px 0’;
item.style.borderLeft = `4px solid ${color}`;
item.style.backgroundColor = ‘#f8f9fa’;
item.style.borderRadius = ‘4px’;
fragment.appendChild(item);
});
this.container.appendChild(fragment);
}

// 清空列表
clear() {
this.container.innerHTML = ”;
this.items = [];
}

// 搜索项目
search(query) {
return this.items.filter(item =>
item.text.toLowerCase().includes(query.toLowerCase())
);
}
}

// 使用示例
const listManager = new DynamicListManager(‘list-container’);

// 添加单个项目
listManager.addItem(‘学习JavaScript’, ‘#007bff’);
listManager.addItem(‘掌握DOM操作’, ‘#28a745’);
listManager.addItem(‘构建应用’, ‘#ffc107’);

// 批量添加
listManager.addBatch([
{ text: ‘项目A’, color: ‘#17a2b8’ },
{ text: ‘项目B’, color: ‘#6610f2’ },
{ text: ‘项目C’, color: ‘#e83e8c’ }
]);

// 搜索示例
const results = listManager.search(‘项目’);
console.log(‘搜索结果:’, results);
三、DOM修改:动态更新内容与样式
3.1 修改内容
textContent vs innerHTML vs innerText
// HTML结构
//

// 文本内容
// 加粗文本
//

const contentDiv = document.getElementById(‘content’);

// textContent: 获取或设置文本内容,忽略HTML标签
console.log(contentDiv.textContent); // 输出: “文本内容加粗文本”
contentDiv.textContent = ‘新文本‘; // 显示为纯文本,不解析HTML

// innerHTML: 获取或设置HTML内容,解析HTML标签
console.log(contentDiv.innerHTML); // 输出: “文本内容加粗文本”
contentDiv.innerHTML = ‘新文本‘; // 解析为HTML元素

// innerText: 获取或设置可见文本内容(考虑CSS样式)
console.log(contentDiv.innerText); // 输出: “文本内容加粗文本”
contentDiv.innerText = ‘新文本‘; // 显示为纯文本

// 实际应用:安全地设置内容
function safeSetHTML(element, html) {
// 使用textContent防止XSS攻击
if (html.includes(‘

${user.name}

${user.status}

邮箱: ${user.email}

角色: ${user.role}

注册时间: ${new Date(user.registerDate).toLocaleDateString()}

`; return card; }

// 使用示例 const userData = { id: ‘123’, name: ‘张三’, email: ‘zhangsan@example.com’, role: ‘管理员’, status: ‘active’, registerDate: ‘2024-01-15’ };

const userCard = createUserCard(userData); document.getElementById(‘user-list’).appendChild(userCard); 3.2 修改样式 style属性 const element = document.getElementById(‘myElement’);

// 设置单个样式 element.style.color = ‘red’; element.style.backgroundColor = ‘#f0f0f0′; element.style.padding = ’10px’; element.style.borderRadius = ‘5px’;

// 设置多个样式 Object.assign(element.style, { color: ‘white’, backgroundColor: ‘#007bff’, padding: ’12px 20px’, border: ‘none’, borderRadius: ‘4px’, cursor: ‘pointer’, transition: ‘all 0.3s ease’ });

// 动态样式 function setDynamicStyles(element, isActive) { if (isActive) { element.style.backgroundColor = ‘#28a745’; element.style.transform = ‘scale(1.05)’; element.style.boxShadow = ‘0 4px 8px rgba(40, 167, 69, 0.3)’; } else { element.style.backgroundColor = ‘#6c757d’; element.style.transform = ‘scale(1)’; element.style.boxShadow = ‘none’; } } className vs classList // HTML结构 //

内容

const box = document.getElementById(‘box’);

// className: 完全替换类名 box.className = ‘box secondary’; // 替换为”box secondary” box.className += ‘ highlighted’; // 添加类名(注意空格)

// classList: 操作类名集合(推荐) box.classList.add(‘highlighted’); // 添加类名 box.classList.remove(‘primary’); // 移除类名 box.classList.toggle(‘active’); // 切换类名(存在则移除,不存在则添加) box.classList.contains(‘box’); // 检查是否包含类名(返回true/false) box.classList.replace(‘secondary’, ‘success’); // 替换类名

// 实际应用:主题切换 function toggleTheme() { document.body.classList.toggle(‘dark-theme’); document.body.classList.toggle(‘light-theme’);

// 保存主题偏好 const currentTheme = document.body.classList.contains(‘dark-theme’) ? ‘dark’ : ‘light’; localStorage.setItem(‘theme’, currentTheme); }

// 批量操作类名 function setButtonState(button, state) { // 移除所有状态类 button.classList.remove(‘btn-primary’, ‘btn-success’, ‘btn-danger’, ‘btn-warning’);

// 根据状态添加对应的类 switch(state) { case ‘primary’: button.classList.add(‘btn-primary’); break; case ‘success’: button.classList.add(‘btn-success’); break; case ‘danger’: button.classList.add(‘btn-danger’); break; case ‘warning’: button.classList.add(‘btn-warning’); break; } } getComputedStyle() 获取计算后的样式(包括从CSS继承的样式)。 const element = document.getElementById(‘myElement’);

// 获取计算后的样式 const computedStyle = window.getComputedStyle(element); console.log(computedStyle.color); // 输出: rgb(255, 0, 0) 或 #ff0000 console.log(computedStyle.backgroundColor); // 输出: rgb(240, 240, 240) console.log(computedStyle.display); // 输出: block

// 实际应用:动画前获取初始状态 function animateElement(element) { // 获取初始位置 const initialPosition = window.getComputedStyle(element).position; const initialLeft = window.getComputedStyle(element).left;

// 应用动画 element.style.transition = ‘left 1s ease’; element.style.left = ‘100px’;

// 动画结束后恢复 setTimeout(() => { element.style.left = initialLeft; }, 1000); } 3.3 修改属性 setAttribute() vs 直接属性访问 // HTML结构 // 链接

const link = document.getElementById(‘link’);

// 直接属性访问(推荐用于标准属性) link.href = ‘https://newexample.com’; link.title = ‘新的标题’; link.target = ‘_blank’; link.textContent = ‘新链接文本’;

// setAttribute()(用于自定义属性或特殊属性) link.setAttribute(‘data-custom’, ‘custom-value’); link.setAttribute(‘aria-label’, ‘访问链接’); link.setAttribute(‘rel’, ‘noopener noreferrer’);

// 获取属性 const href = link.getAttribute(‘href’); // “https://newexample.com” const customData = link.dataset.custom; // “custom-value” (推荐使用dataset)

// 检查属性是否存在 const hasTitle = link.hasAttribute(‘title’); // true const hasCustom = link.hasAttribute(‘data-custom’); // true

// 移除属性 link.removeAttribute(‘title’); link.removeAttribute(‘data-custom’); dataset属性(操作data-*属性) // HTML结构 //

用户

const userDiv = document.getElementById(‘user’);

// 读取data属性 console.log(userDiv.dataset.userId); // “123” console.log(userDiv.dataset.role); // “admin” console.log(userdiv.dataset.status); // “active”

// 设置data属性 userDiv.dataset.userId = ‘456’; userDiv.dataset.role = ‘moderator’; userDiv.dataset.newField = ‘newValue’;

// 结果:

用户

// 实际应用:基于数据属性的查询和操作 function filterUsersByRole(role) { const users = document.querySelectorAll(‘[data-role]’); users.forEach(user => { if (user.dataset.role === role) { user.style.display = ‘block’; user.style.backgroundColor = ‘#e8f5e9’; } else { user.style.display = ‘none’; } }); }

// 批量更新数据属性 function updateUserStatus(status) { const users = document.querySelectorAll(‘[data-status]’); users.forEach(user => { user.dataset.status = status; // 根据状态更新样式 switch(status) { case ‘active’: user.style.color = ‘green’; break; case ‘inactive’: element.style.color = ‘gray’; break; case ‘banned’: user.style.color = ‘red’; break; } }); } 3.4 实战应用:表单验证与动态反馈 // 完整的表单验证类 class FormValidator { constructor(formId) { this.form = document.getElementById(formId); this.errors = {}; this.setupValidation(); }

setupValidation() { // 为所有输入框添加实时验证 const inputs = this.form.querySelectorAll(‘input, textarea, select’); inputs.forEach(input => { input.addEventListener(‘blur’, () => this.validateField(input)); input.addEventListener(‘input’, () => this.clearError(input)); });

// 表单提交验证 this.form.addEventListener(‘submit’, (e) => { e.preventDefault(); if (this.validateForm()) { this.submitForm(); } }); }

validateField(field) { const value = field.value.trim(); const type = field.type; const name = field.name; let error = ”;

// 根据类型验证 if (field.hasAttribute(‘required’) && !value) { error = ‘此字段为必填项’; } else if (type === ’email’ && value && !value.includes(‘@’)) { error = ‘请输入有效的邮箱地址’; } else if (type === ‘password’ && value.length < 6) { error = '密码长度至少为6位'; } else if (name === 'phone' && value && !/^\d{11}$/.test(value)) { error = '请输入11位手机号'; } // 显示或清除错误 if (error) { this.showError(field, error); return false; } else { this.clearError(field); return true; } } showError(field, message) { // 移除之前的错误状态 this.clearError(field); // 添加错误样式 field.style.borderColor = '#dc3545'; field.style.backgroundColor = '#fff5f5'; // 创建错误信息元素 const errorElement = document.createElement('div'); errorElement.className = 'error-message'; errorElement.textContent = message; errorElement.style.color = '#dc3545'; errorElement.style.fontSize = '12px'; errorElement.style.marginTop = '4px'; errorElement.style.padding = '4px'; errorElement.style.backgroundColor = '#ffe6e6'; errorElement.style.borderRadius = '3px'; // 插入到字段后面 field.parentNode.insertBefore(errorElement, field.nextSibling); // 保存错误引用 this.errors[field.name] = errorElement; } clearError(field) { // 恢复样式 field.style.borderColor = ''; field.style.backgroundColor = ''; // 移除错误信息 if (this.errors[field.name]) { this.errors[field.name].remove(); delete this.errors[field.name]; } } validateForm() { const inputs = this.form.querySelectorAll('input, textarea, select'); let isValid = true; inputs.forEach(input => { if (!this.validateField(input)) { isValid = false; } });

return isValid; }

submitForm() { // 收集表单数据 const formData = new FormData(this.form); const data = Object.fromEntries(formData.entries());

// 显示成功消息 this.showSuccess(‘表单提交成功!’);

// 模拟提交 console.log(‘提交的数据:’, data);

// 重置表单 setTimeout(() => { this.form.reset(); this.clearAllErrors(); }, 2000); }

showSuccess(message) { const successDiv = document.createElement(‘div’); successDiv.className = ‘success-message’; successDiv.textContent = message; successDiv.style.padding = ’10px’; successDiv.style.margin = ’10px 0′; successDiv.style.backgroundColor = ‘#d4edda’; successDiv.style.color = ‘#155724’; successDiv.style.border = ‘1px solid #c3e6cb’; successDiv.style.borderRadius = ‘4px’; successDiv.style.transition = ‘all 0.3s ease’;

this.form.parentNode.insertBefore(successDiv, this.form);

// 3秒后移除 setTimeout(() => { successDiv.style.opacity = ‘0’; setTimeout(() => successDiv.remove(), 300); }, 3000); }

clearAllErrors() { Object.keys(this.errors).forEach(fieldName => { const field = this.form.querySelector(`[name=”${fieldName}”]`); if (field) this.clearError(field); }); } }

// 使用示例 const validator = new FormValidator(‘registration-form’); 四、DOM删除:安全移除元素 4.1 基本删除方法 removeChild() // HTML结构 //

// 要删除的元素 // 保留的元素 //

const parent = document.getElementById(‘parent’); const child = document.getElementById(‘child’);

// 删除子元素 parent.removeChild(child);

// 或者直接使用remove()(现代浏览器) child.remove(); remove() // 现代浏览器支持直接删除 const element = document.getElementById(‘element-to-remove’); element.remove(); // 直接删除自身

// 批量删除 const elementsToRemove = document.querySelectorAll(‘.obsolete’); elementsToRemove.forEach(el => el.remove()); 4.2 高级删除技巧 带确认的删除 // 确认对话框 function confirmDelete(element, message = ‘确定要删除吗?’) { if (confirm(message)) { // 添加删除动画 element.style.transition = ‘all 0.3s ease’; element.style.opacity = ‘0’; element.style.transform = ‘scale(0.8)’;

setTimeout(() => { element.remove(); console.log(‘元素已删除’); }, 300); } }

// 使用示例 const deleteBtn = document.getElementById(‘delete-btn’); deleteBtn.addEventListener(‘click’, () => { const item = document.getElementById(‘item-to-delete’); confirmDelete(item, ‘确定要删除这个项目吗?’); }); 条件删除 // 删除所有满足条件的元素 function deleteByCondition(selector, condition) { const elements = document.querySelectorAll(selector); elements.forEach(element => { if (condition(element)) { element.remove(); } }); }

// 示例:删除所有空段落 deleteByCondition(‘p’, p => p.textContent.trim() === ”);

// 示例:删除所有过期的项目 deleteByCondition(‘[data-expired]’, el => { const expiryDate = new Date(el.dataset.expiry); return expiryDate < new Date(); }); 恢复删除(撤销功能) // 实现撤销删除功能 class DeleteManager { constructor() { this.deletedElements = []; } deleteWithUndo(element) { // 保存元素的完整信息 const elementInfo = { element: element, parent: element.parentElement, nextSibling: element.nextSibling, html: element.outerHTML }; // 执行删除 element.remove(); this.deletedElements.push(elementInfo); // 显示撤销提示 this.showUndoNotification(); } showUndoNotification() { // 移除之前的提示 const existing = document.getElementById('undo-notification'); if (existing) existing.remove(); // 创建新提示 const notification = document.createElement('div'); notification.id = 'undo-notification'; notification.innerHTML = ` 元素已删除 `; notification.style.position = ‘fixed’; notification.style.bottom = ’20px’; notification.style.right = ’20px’; notification.style.padding = ’10px 15px’; notification.style.backgroundColor = ‘#333’; notification.style.color = ‘white’; notification.style.borderRadius = ‘4px’; notification.style.zIndex = ‘1000’; notification.style.boxShadow = ‘0 2px 8px rgba(0,0,0,0.3)’;

document.body.appendChild(notification);

// 绑定撤销事件 document.getElementById(‘undo-btn’).addEventListener(‘click’, () => this.undo());

// 5秒后自动隐藏 setTimeout(() => { notification.style.opacity = ‘0’; setTimeout(() => notification.remove(), 300); }, 5000); }

undo() { if (this.deletedElements.length === 0) return;

const lastDeleted = this.deletedElements.pop();

// 重新插入到原来位置 if (lastDeleted.nextSibling) { lastDeleted.parent.insertBefore(lastDeleted.element, lastDeleted.nextSibling); } else { lastDeleted.parent.appendChild(lastDeleted.element); }

// 移除提示 const notification = document.getElementById(‘undo-notification’); if (notification) notification.remove();

// 恢复动画 lastDeleted.element.style.transition = ‘all 0.3s ease’; lastDeleted.element.style.opacity = ‘1’; lastDeleted.element.style.transform = ‘scale(1)’; }

// 清空历史 clearHistory() { this.deletedElements = []; } }

// 使用示例 const deleteManager = new DeleteManager(); const item = document.getElementById(‘item-1’); deleteManager.deleteWithUndo(item); 4.3 实战应用:购物车管理 // 购物车类 class ShoppingCart { constructor(containerId) { this.container = document.getElementById(containerId); this.items = []; this.totalElement = document.getElementById(‘cart-total’); }

// 添加商品 addItem(product) { // 检查是否已存在 const existingItem = this.items.find(item => item.id === product.id); if (existingItem) { existingItem.quantity++; this.updateItemDisplay(existingItem); } else { // 创建新项目 const cartItem = { …product, quantity: 1, element: this.createCartItemElement(product) }; this.items.push(cartItem); this.container.appendChild(cartItem.element); }

this.updateTotal(); this.showNotification(‘商品已添加到购物车’); }

createCartItemElement(product) { const itemDiv = document.createElement(‘div’); itemDiv.className = ‘cart-item’; itemDiv.dataset.productId = product.id; itemDiv.style.display = ‘flex’; itemDiv.style.justifyContent = ‘space-between’; itemDiv.style.alignItems = ‘center’; itemDiv.style.padding = ’10px’; itemDiv.style.borderBottom = ‘1px solid #eee’;

itemDiv.innerHTML = `

${product.name}

单价: ¥${product.price}

1

`;

// 绑定事件 itemDiv.querySelector(‘.increase’).addEventListener(‘click’, () => this.increaseQuantity(product.id)); itemDiv.querySelector(‘.decrease’).addEventListener(‘click’, () => this.decreaseQuantity(product.id)); itemDiv.querySelector(‘.remove’).addEventListener(‘click’, () => this.removeItem(product.id));

return itemDiv; }

// 增加数量 increaseQuantity(productId) { const item = this.items.find(item => item.id === productId); if (item) { item.quantity++; this.updateItemDisplay(item); this.updateTotal(); } }

// 减少数量 decreaseQuantity(productId) { const item = this.items.find(item => item.id === productId); if (item && item.quantity > 1) { item.quantity–; this.updateItemDisplay(item); this.updateTotal(); } else { this.removeItem(productId); } }

// 更新项目显示 updateItemDisplay(item) { const quantitySpan = item.element.querySelector(‘.quantity’); quantitySpan.textContent = item.quantity;

// 添加动画效果 quantitySpan.style.transform = ‘scale(1.2)’; quantitySpan.style.color = ‘#28a745’; setTimeout(() => { quantitySpan.style.transform = ‘scale(1)’; quantitySpan.style.color = ”; }, 200); }

// 删除项目 removeItem(productId) { const itemIndex = this.items.findIndex(item => item.id === productId); if (itemIndex === -1) return;

const item = this.items[itemIndex];

// 添加删除动画 item.element.style.transition = ‘all 0.3s ease’; item.element.style.opacity = ‘0’; item.element.style.transform = ‘translateX(20px)’;

setTimeout(() => { // 从DOM中移除 item.element.remove();

// 从数组中移除 this.items.splice(itemIndex, 1);

// 更新总价 this.updateTotal();

// 显示通知 this.showNotification(‘商品已从购物车删除’); }, 300); }

// 清空购物车 clearCart() { if (this.items.length === 0) return;

if (confirm(‘确定要清空购物车吗?’)) { // 批量删除 this.items.forEach(item => { item.element.style.transition = ‘all 0.3s ease’; item.element.style.opacity = ‘0’; item.element.style.transform = ‘translateX(20px)’; });

setTimeout(() => { this.items.forEach(item => item.element.remove()); this.items = []; this.updateTotal(); this.showNotification(‘购物车已清空’); }, 300); } }

// 更新总价 updateTotal() { const total = this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0); if (this.totalElement) { this.totalElement.textContent = `总计: ¥${total.toFixed(2)}`; } }

// 显示通知 showNotification(message) { const notification = document.createElement(‘div’); notification.textContent = message; notification.style.position = ‘fixed’; notification.style.top = ’20px’; notification.style.right = ’20px’; notification.style.padding = ’10px 15px’; notification.style.backgroundColor = ‘#28a745’; notification.style.color = ‘white’; notification.style.borderRadius = ‘4px’; notification.style.zIndex = ‘1000’; notification.style.boxShadow = ‘0 2px 8px rgba(0,0,0,0.3)’; notification.style.transition = ‘all 0.3s ease’;

document.body.appendChild(notification);

setTimeout(() => { notification.style.opacity = ‘0’; notification.style.transform = ‘translateY(-10px)’; setTimeout(() => notification.remove(), 300); }, 2000); } }

// 使用示例 const cart = new ShoppingCart(‘cart-container’);

// 添加商品 cart.addItem({ id: 1, name: ‘iPhone 15’, price: 5999 }); cart.addItem({ id: 2, name: ‘MacBook Pro’, price: 12999 }); cart.addItem({ id: 3, name: ‘AirPods’, price: 1299 });

// 清空购物车按钮 document.getElementById(‘clear-cart-btn’).addEventListener(‘click’, () => cart.clearCart()); 五、综合实战:构建动态任务管理器 5.1 项目结构与初始化 // 任务管理器类 class TaskManager { constructor(containerId) { this.container = document.getElementById(containerId); this.tasks = []; this.filter = ‘all’; // all, active, completed this.nextId = 1; this.init(); }

init() { // 创建UI结构 this.createUI(); // 绑定事件 this.bindEvents(); // 加载本地存储 this.loadFromStorage(); }

createUI() { // 清空容器 this.container.innerHTML = ”;

// 创建输入区域 const inputSection = document.createElement(‘div’); inputSection.className = ‘task-input-section’; inputSection.style.marginBottom = ’20px’; inputSection.innerHTML = ` `; inputSection.style.display = ‘flex’;

// 创建过滤区域 const filterSection = document.createElement(‘div’); filterSection.className = ‘filter-section’; filterSection.style.marginBottom = ’10px’; filterSection.innerHTML = ` `;

// 创建任务列表容器 const taskListContainer = document.createElement(‘div’); taskListContainer.id = ‘task-list’; taskListContainer.style.minHeight = ‘200px’;

// 创建统计信息 const statsSection = document.createElement(‘div’); statsSection.id = ‘task-stats’; statsSection.style.marginTop = ’20px’; statsSection.style.padding = ’10px’; statsSection.style.backgroundColor = ‘#f8f9fa’; statsSection.style.borderRadius = ‘4px’; statsSection.style.fontSize = ’14px’;

// 组装UI this.container.appendChild(inputSection); this.container.appendChild(filterSection); this.container.appendChild(taskListContainer); this.container.appendChild(statsSection); }

bindEvents() { // 添加任务按钮 const addBtn = this.container.querySelector(‘#add-task-btn’); addBtn.addEventListener(‘click’, () => this.addTask());

// 输入框回车 const input = this.container.querySelector(‘#task-input’); input.addEventListener(‘keypress’, (e) => { if (e.key === ‘Enter’) this.addTask(); });

// 过滤按钮 const filterButtons = this.container.querySelectorAll(‘[data-filter]’); filterButtons.forEach(btn => { btn.addEventListener(‘click’, (e) => { this.filter = e.target.dataset.filter; this.render(); }); });

// 清除已完成按钮 const clearBtn = this.container.querySelector(‘#clear-completed-btn’); clearBtn.addEventListener(‘click’, () => this.clearCompleted()); }

addTask() { const input = this.container.querySelector(‘#task-input’); const text = input.value.trim();

if (!text) { alert(‘请输入任务内容’); return; }

const task = { id: this.nextId++, text: text, completed: false, createdAt: new Date().toISOString() };

this.tasks.push(task); input.value = ”; this.render(); this.saveToStorage(); this.showNotification(‘任务添加成功’); }

toggleTask(id) { const task = this.tasks.find(t => t.id === id); if (task) { task.completed = !task.completed; this.render(); this.saveToStorage(); } }

deleteTask(id) { const taskElement = this.container.querySelector(`[data-task-id=”${id}”]`); if (!taskElement) return;

// 添加删除动画 taskElement.style.transition = ‘all 0.3s ease’; taskElement.style.opacity = ‘0’; taskElement.style.transform = ‘translateX(-20px)’;

setTimeout(() => { this.tasks = this.tasks.filter(t => t.id !== id); this.render(); this.saveToStorage(); this.showNotification(‘任务已删除’); }, 300); }

clearCompleted() { const completedTasks = this.tasks.filter(t => t.completed); if (completedTasks.length === 0) { alert(‘没有已完成的任务’); return; }

if (confirm(`确定要清除 ${completedTasks.length} 个已完成的任务吗?`)) { // 批量删除动画 completedTasks.forEach(task => { const taskElement = this.container.querySelector(`[data-task-id=”${task.id}”]`); if (taskElement) { taskElement.style.transition = ‘all 0.3s ease’; taskElement.style.opacity = ‘0’; taskElement.style.transform = ‘translateX(-20px)’; } });

setTimeout(() => { this.tasks = this.tasks.filter(t => !t.completed); this.render(); this.saveToStorage(); this.showNotification(‘已清除所有已完成任务’); }, 300); } }

render() { const taskList = this.container.querySelector(‘#task-list’); const stats = this.container.querySelector(‘#task-stats’);

// 过滤任务 let filteredTasks = this.tasks; if (this.filter === ‘active’) { filteredTasks = this.tasks.filter(t => !t.completed); } else if (this.filter === ‘completed’) { filteredTasks = this.tasks.filter(t => t.completed); }

// 清空列表 taskList.innerHTML = ”;

// 创建文档片段 const fragment = document.createDocumentFragment();

// 渲染任务 if (filteredTasks.length === 0) { const emptyMsg = document.createElement(‘div’); emptyMsg.textContent = ‘暂无任务’; emptyMsg.style.textAlign = ‘center’; emptyMsg.style.padding = ’40px’; emptyMsg.style.color = ‘#999’; fragment.appendChild(emptyMsg); } else { filteredTasks.forEach(task => { const taskElement = this.createTaskElement(task); fragment.appendChild(taskElement); }); }

taskList.appendChild(fragment);

// 更新统计 this.updateStats(stats); }

createTaskElement(task) { const div = document.createElement(‘div’); div.className = ‘task-item’; div.dataset.taskId = task.id; div.style.display = ‘flex’; div.style.alignItems = ‘center’; div.style.padding = ’12px’; div.style.marginBottom = ‘8px’; div.style.borderRadius = ‘4px’; div.style.borderLeft = ‘4px solid’; div.style.borderLeftColor = task.completed ? ‘#28a745’ : ‘#007bff’; div.style.backgroundColor = task.completed ? ‘#e8f5e9’ : ‘#f8f9fa’; div.style.transition = ‘all 0.3s ease’;

// 复选框 const checkbox = document.createElement(‘input’); checkbox.type = ‘checkbox’; checkbox.checked = task.completed; checkbox.style.marginRight = ’10px’; checkbox.style.cursor = ‘pointer’; checkbox.addEventListener(‘change’, () => this.toggleTask(task.id));

// 任务文本 const textSpan = document.createElement(‘span’); textSpan.textContent = task.text; textSpan.style.flex = ‘1’; textSpan.style.textDecoration = task.completed ? ‘line-through’ : ‘none’; textSpan.style.color = task.completed ? ‘#6c757d’ : ‘#333’;

// 删除按钮 const deleteBtn = document.createElement(‘button’); deleteBtn.textContent = ‘删除’; deleteBtn.style.padding = ‘4px 8px’; deleteBtn.style.backgroundColor = ‘#dc3545’; deleteBtn.style.color = ‘white’; deleteBtn.style.border = ‘none’; deleteBtn.style.borderRadius = ‘3px’; deleteBtn.style.cursor = ‘pointer’; deleteBtn.style.marginLeft = ’10px’; deleteBtn.addEventListener(‘click’, () => this.deleteTask(task.id));

div.appendChild(checkbox); div.appendChild(textSpan); div.appendChild(deleteBtn);

return div; }

updateStats(statsElement) { const total = this.tasks.length; const completed = this.tasks.filter(t => t.completed).length; const active = total – completed;

statsElement.innerHTML = ` 统计: 总计 ${total} | 进行中 ${active} | 已完成 ${completed} `; }

saveToStorage() { localStorage.setItem(‘taskManager_tasks’, JSON.stringify(this.tasks)); localStorage.setItem(‘taskManager_nextId’, this.nextId.toString()); }

loadFromStorage() { const savedTasks = localStorage.getItem(‘taskManager_tasks’); const savedNextId = localStorage.getItem(‘taskManager_nextId’);

if (savedTasks) { this.tasks = JSON.parse(savedTasks); }

if (savedNextId) { this.nextId = parseInt(savedNextId); }

this.render(); }

showNotification(message) { const notification = document.createElement(‘div’); notification.textContent = message; notification.style.position = ‘fixed’; notification.style.top = ’20px’; notification.style.left = ‘50%’; notification.style.transform = ‘translateX(-50%)’; notification.style.padding = ’10px 20px’; notification.style.backgroundColor = ‘#28a745’; notification.style.color = ‘white’; notification.style.borderRadius = ‘4px’; notification.style.zIndex = ‘1000’; notification.style.boxShadow = ‘0 2px 8px rgba(0,0,0,0.3)’; notification.style.transition = ‘all 0.3s ease’;

document.body.appendChild(notification);

setTimeout(() => { notification.style.opacity = ‘0’; notification.style.transform = ‘translateX(-50%) translateY(-10px)’; setTimeout(() => notification.remove(), 300); }, 2000); } }

// 使用示例 const taskManager = new TaskManager(‘task-manager-container’); 5.2 完整的HTML结构示例 任务管理器 – DOM操作实战

任务管理器




六、性能优化与最佳实践
6.1 减少DOM操作次数
// ❌ 不好的做法:多次操作DOM
function badPractice() {
const container = document.getElementById(‘container’);
for (let i = 0; i < 100; i++) { const div = document.createElement('div'); div.textContent = i; container.appendChild(div); // 每次都会触发重排 } } // ✅ 好的做法:使用DocumentFragment function goodPractice() { const container = document.getElementById('container'); const fragment = document.createDocumentFragment(); for (let i = 0; i < 100; i++) { const div = document.createElement('div'); div.textContent = i; fragment.appendChild(div); } container.appendChild(fragment); // 只触发一次重排 } // ✅ 更好的做法:使用innerHTML(适用于简单内容) function bestPractice() { const container = document.getElementById('container'); const html = Array.from({ length: 100 }, (_, i) => `

${i}

`).join(”);
container.innerHTML = html; // 一次性设置
}
6.2 事件委托
// ❌ 不好的做法:为每个元素绑定事件
function badEventPractice() {
const buttons = document.querySelectorAll(‘.item-btn’);
buttons.forEach(btn => {
btn.addEventListener(‘click’, handleClick);
});
}

// ✅ 好的做法:事件委托
function goodEventPractice() {
const container = document.getElementById(‘button-container’);
container.addEventListener(‘click’, function(e) {
if (e.target.classList.contains(‘item-btn’)) {
handleClick(e);
}
});
}

// 更通用的事件委托
function setupEventDelegation(container, selector, eventType, handler) {
container.addEventListener(eventType, function(e) {
const target = e.target.closest(selector);
if (target && container.contains(target)) {
handler(e, target);
}
});
}

// 使用示例
const list = document.getElementById(‘my-list’);
setupEventDelegation(list, ‘button.delete’, ‘click’, (e, button) => {
const itemId = button.dataset.id;
console.log(‘删除项目:’, itemId);
});
6.3 缓存DOM查询结果
// ❌ 不好的做法:重复查询
function badCache() {
document.getElementById(‘header’).style.color = ‘red’;
document.getElementById(‘header’).style.fontSize = ’20px’;
document.getElementById(‘header’).textContent = ‘新标题’;
}

// ✅ 好的做法:缓存引用
function goodCache() {
const header = document.getElementById(‘header’);
header.style.color = ‘red’;
header.style.fontSize = ’20px’;
header.textContent = ‘新标题’;
}

// 在循环中缓存
function cacheInLoop() {
const container = document.getElementById(‘container’);
const items = container.querySelectorAll(‘.item’); // 缓存查询结果

for (let i = 0; i < items.length; i++) { // 使用缓存的length items[i].style.display = 'block'; } } 6.4 使用requestAnimationFrame进行动画 // ❌ 不好的做法:直接修改样式 function badAnimation(element) { let start = null; function step(timestamp) { if (!start) start = timestamp; const progress = timestamp - start; element.style.left = Math.min(progress / 10, 100) + 'px'; if (progress < 1000) { window.requestAnimationFrame(step); } } window.requestAnimationFrame(step); } // ✅ 好的做法:使用transform和opacity(GPU加速) function goodAnimation(element) { let start = null; function step(timestamp) { if (!start) start = timestamp; const progress = timestamp - start; const percentage = Math.min(progress / 1000, 1); // 使用transform而不是left/top element.style.transform = `translateX(${percentage * 100}px)`; element.style.opacity = percentage; if (progress < 1000) { window.requestAnimationFrame(step); } } window.requestAnimationFrame(step); } 6.5 防抖与节流 // 防抖:适用于搜索框输入 function debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => {
clearTimeout(timeout);
func(…args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}

// 节流:适用于滚动事件
function throttle(func, limit) {
let inThrottle;
return function(…args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}

// 使用示例
const searchInput = document.getElementById(‘search’);
searchInput.addEventListener(‘input’, debounce(function(e) {
console.log(‘搜索:’, e.target.value);
// 执行搜索逻辑
}, 300));

const scrollContainer = document.getElementById(‘scroll-container’);
scrollContainer.addEventListener(‘scroll’, throttle(function() {
console.log(‘滚动位置:’, this.scrollTop);
// 执行滚动相关的逻辑
}, 100));
七、常见问题与解决方案
7.1 事件监听器管理
// 避免内存泄漏:正确移除事件监听器
class EventManager {
constructor() {
this.listeners = new Map();
}

addListener(element, event, handler) {
// 存储监听器引用
const key = `${element}-${event}`;
this.listeners.set(key, handler);

element.addEventListener(event, handler);
}

removeListener(element, event) {
const key = `${element}-${event}`;
const handler = this.listeners.get(key);

if (handler) {
element.removeEventListener(event, handler);
this.listeners.delete(key);
}
}

removeAllListeners() {
this.listeners.forEach((handler, key) => {
const [element, event] = key.split(‘-‘);
element.removeEventListener(event, handler);
});
this.listeners.clear();
}
}

// 使用示例
const eventManager = new EventManager();
const button = document.getElementById(‘my-btn’);

eventManager.addListener(button, ‘click’, () => console.log(‘点击’));
// 清理时
eventManager.removeAllListeners();
7.2 处理动态内容中的事件
// 动态内容的事件绑定问题
// ❌ 错误:直接绑定会失效
function badDynamicEvents() {
const container = document.getElementById(‘container’);
container.innerHTML = ‘‘;
document.getElementById(‘new-btn’).addEventListener(‘click’, () => {
console.log(‘这不会工作’);
});
}

// ✅ 正确:使用事件委托
function goodDynamicEvents() {
const container = document.getElementById(‘container’);

// 先绑定委托事件
container.addEventListener(‘click’, function(e) {
if (e.target.id === ‘new-btn’) {
console.log(‘这会工作’);
}
});

// 再动态添加内容
container.innerHTML = ‘‘;
}
7.3 跨浏览器兼容性
// 现代浏览器已经不需要太多兼容性处理,但仍需注意
function crossBrowserDOM() {
// classList在IE9+支持,但IE10才支持第二个参数
const element = document.getElementById(‘my-element’);

// 安全的class操作
if (element.classList) {
element.classList.add(‘active’);
element.classList.remove(‘old’);
element.classList.toggle(‘new’);
} else {
// 降级处理
const className = element.className;
if (className.indexOf(‘active’) === -1) {
element.className += ‘ active’;
}
}

// querySelectorAll在IE8+支持
// getElementsByClassName在IE9+支持
// textContent在IE9+支持
// innerText在IE4+支持(但行为略有不同)
}
7.4 处理大量数据渲染
// 虚拟滚动(适用于大量数据)
class VirtualScroll {
constructor(container, itemHeight, totalItems, renderItem) {
this.container = container;
this.itemHeight = itemHeight;
this.totalItems = totalItems;
this.renderItem = renderItem;
this.visibleCount = 0;
this.scrollTop = 0;

this.init();
}

init() {
// 设置容器高度
this.container.style.height = ‘400px’;
this.container.style.overflow = ‘auto’;
this.container.style.position = ‘relative’;

// 计算可见数量
this.visibleCount = Math.ceil(400 / this.itemHeight) + 2;

// 创建占位元素
this.spacer = document.createElement(‘div’);
this.spacer.style.height = `${this.totalItems * this.itemHeight}px`;
this.spacer.style.position = ‘absolute’;
this.spacer.style.top = ‘0’;
this.spacer.style.left = ‘0’;
this.spacer.style.width = ‘100%’;
this.container.appendChild(this.spacer);

// 创建内容容器
this.content = document.createElement(‘div’);
this.content.style.position = ‘absolute’;
this.content.style.top = ‘0’;
this.content.style.left = ‘0’;
this.content.style.width = ‘100%’;
this.container.appendChild(this.content);

// 绑定滚动事件
this.container.addEventListener(‘scroll’, () => this.render());

// 初始渲染
this.render();
}

render() {
const scrollTop = this.container.scrollTop;
const startIndex = Math.floor(scrollTop / this.itemHeight);
const endIndex = Math.min(startIndex + this.visibleCount, this.totalItems);

// 更新内容容器位置
this.content.style.top = `${startIndex * this.itemHeight}px`;

// 渲染可见项目
let html = ”;
for (let i = startIndex; i < endIndex; i++) { html += this.renderItem(i); } this.content.innerHTML = html; } } // 使用示例 const container = document.getElementById('virtual-list'); const virtualScroll = new VirtualScroll( container, 40, // 每项高度 10000, // 总项数 (index) => `

项目 ${index + 1}

`
);
八、总结
通过本文的详细讲解和大量实战代码示例,我们全面掌握了JavaScript DOM操作的核心技巧。从基础的增删改查到高级的性能优化,从简单的元素操作到复杂的动态应用构建,这些知识将帮助你构建高效、响应式的Web应用。
核心要点回顾:
查询元素
:优先使用
querySelector
和
querySelectorAll
,它们语法更灵活,性能良好
创建元素
:批量操作时使用
DocumentFragment
减少回流
修改内容
:注意
textContent
和
innerHTML
的安全性差异
样式操作
:优先使用
classList
而不是
className
,使用
transform
和
opacity
进行动画
事件处理
:使用事件委托处理动态内容,注意内存泄漏
性能优化
:缓存DOM查询,减少重排重绘,使用防抖节流
实际应用建议:
在构建复杂应用时,考虑使用MVC/MVVM模式分离DOM操作逻辑
对于大型项目,可以考虑使用现代框架(React、Vue等),但理解原生DOM操作仍然至关重要
始终考虑用户体验,添加适当的动画和反馈
注意可访问性(Accessibility),使用ARIA属性
掌握这些DOM操作技巧,你将能够构建出高效、优雅的Web应用,无论是简单的页面交互还是复杂的单页应用,都能游刃有余。