1. DOM overview

DOM (Document Object Model, documentationobjectmodel) is HTML and XML documentation programminginterface. 它providing了一种structure化 documentation表示method, 使程序able to访问 and modifydocumentation in 容, structure and 样式.

in 浏览器in, DOM 将 HTML documentation解析 for 一个由node and object组成 tree状structure, 称 for DOM tree. JavaScript 可以through DOM API and 这个tree状structurefor交互.

2. DOM treestructure

DOM tree由以 under 几种class型 node组成:

  • documentationnode (Document) : 整个documentation 根node
  • 元素node (Element) : HTML tag, such as <div>, <p> etc.
  • 文本node (Text) : 元素in 文本 in 容
  • propertynode (Attribute) : 元素 property, such as id, class etc.
  • commentnode (Comment) : HTML comment

例such as, 一个 simple HTML documentation会被解析 for such as under DOM tree:

<!DOCTYPE html> <html> <head> <title>example页面</title> </head> <body> <h1>欢迎</h1> <p>这 is a example</p> </body> </html>

for 应 DOM treestructure:

Document └── html ├── head │ └── title │ └── Text: "example页面" └── body ├── h1 │ └── Text: "欢迎" └── p └── Text: "这 is a example"

3. 选择 DOM 元素

JavaScript providing了 many 种method来选择 DOM 元素:

3.1 through ID 选择

// through ID 选择元素 const element = document.getElementById('myElement'); console.log(element);

3.2 throughclass名选择

// throughclass名选择元素 (返回 NodeList) const elements = document.getElementsByClassName('myClass'); console.log(elements); // 遍历 NodeList for (let i = 0; i < elements.length; i++) { console.log(elements[i]); }

3.3 through标signature选择

// through标signature选择元素 (返回 HTMLCollection) const paragraphs = document.getElementsByTagName('p'); console.log(paragraphs);

3.4 through CSS 选择器选择

// through CSS 选择器选择单个元素 const element = document.querySelector('.myClass'); console.log(element); // through CSS 选择器选择 many 个元素 (返回 NodeList) const elements = document.querySelectorAll('div.myClass'); console.log(elements); // 遍历 NodeList elements.forEach(element => { console.log(element); });

4. modify DOM 元素

4.1 modify元素 in 容

// modify元素 文本 in 容 const element = document.getElementById('myElement'); element.textContent = ' new 文本 in 容'; // modify元素 HTML in 容 element.innerHTML = '加粗文本'; // 获取元素 文本 in 容 console.log(element.textContent); // 获取元素 HTML in 容 console.log(element.innerHTML);

4.2 modify元素property

// 获取元素 const link = document.getElementById('myLink'); // 获取property值 console.log(link.getAttribute('href')); // 设置property值 link.setAttribute('href', 'https://www.example.com'); link.setAttribute('target', '_blank'); // 移除property link.removeAttribute('target'); // checkproperty is 否存 in console.log(link.hasAttribute('href')); // true console.log(link.hasAttribute('target')); // false // 直接访问 in 置property link.href = 'https://www.google.com'; link.title = '访问 Google';

4.3 modify元素样式

// 获取元素 const element = document.getElementById('myElement'); // through style propertymodify in 联样式 element.style.color = 'red'; element.style.fontSize = '18px'; element.style.backgroundColor = '#f0f0f0'; element.style.padding = '10px'; // 添加 CSS class element.classList.add('highlight'); // 移除 CSS class element.classList.remove('highlight'); // 切换 CSS class element.classList.toggle('highlight'); // check元素 is 否package含某个class console.log(element.classList.contains('highlight'));

5. creation and delete元素

5.1 creation元素

// creation new 元素 const newDiv = document.createElement('div'); // 设置元素property newDiv.id = 'newElement'; newDiv.className = 'container'; // 设置元素 in 容 newDiv.textContent = '这 is a new creation 元素'; // 添加 to DOM in const parent = document.getElementById('parentElement'); parent.appendChild(newDiv); // in 指定位置插入元素 const referenceElement = document.getElementById('reference'); parent.insertBefore(newDiv, referenceElement);

5.2 delete元素

// 获取要delete 元素 const elementToRemove = document.getElementById('elementToRemove'); // 获取父元素 const parent = elementToRemove.parentElement; // delete元素 parent.removeChild(elementToRemove); // or 者using remove() method (现代浏览器support) elementToRemove.remove();

5.3 clone元素

// 获取要clone 元素 const originalElement = document.getElementById('original'); // clone元素 (不package含子元素) const clone1 = originalElement.cloneNode(false); // clone元素 (package含子元素) const clone2 = originalElement.cloneNode(true); // 添加clone 元素 to DOM const parent = document.getElementById('parent'); parent.appendChild(clone2);

6. DOM 遍历

DOM 遍历 is 指 in DOM treeinmove, 访问不同 node. 以 under is 一些常用 DOM 遍历method:

6.1 noderelationships

// 获取元素 const element = document.getElementById('myElement'); // 父node element.parentElement; element.parentNode; // 子node element.children; // 只package含元素node element.childNodes; // package含所 has class型 node // 第一个 and 最 after 一个子元素 element.firstElementChild; element.lastElementChild; // 相邻node element.previousElementSibling; element.nextElementSibling; element.previousSibling; element.nextSibling;

6.2 遍历example

// 遍历所 has 子元素 const parent = document.getElementById('parent'); for (let i = 0; i < parent.children.length; i++) { console.log(parent.children[i]); } // 递归遍历所 has after 代元素 function traverseDOM(element) { console.log(element); const children = element.children; for (let i = 0; i < children.length; i++) { traverseDOM(children[i]); } } traverseDOM(document.body);

7. DOM eventBasics

DOM event is user and 网页交互时发生 动作, such as点击, 鼠标move, 键盘输入etc.. JavaScript 可以throughevent监听器来response这些event.

7.1 添加event监听器

// 获取元素 const button = document.getElementById('myButton'); // 添加event监听器 button.addEventListener('click', function() { console.log('按钮被点击了!'); }); // using箭头function button.addEventListener('click', () => { console.log('按钮被点击了 (箭头function) !'); }); // 带parameter eventprocessingfunction function handleClick(event) { console.log('点击event:', event); console.log('点击 元素:', event.target); } button.addEventListener('click', handleClick);

7.2 移除event监听器

// 获取元素 const button = document.getElementById('myButton'); // 定义eventprocessingfunction function handleClick() { console.log('按钮被点击了!'); } // 添加event监听器 button.addEventListener('click', handleClick); // 移除event监听器 button.removeEventListener('click', handleClick);

8. DOM operationoptimization

DOM operation is 昂贵 , 频繁 DOM operation会导致页面performance under 降. 以 under is 一些optimizationtechniques:

8.1 reducing DOM 访问

// 不推荐: 频繁访问 DOM for (let i = 0; i < 1000; i++) { document.getElementById('counter').textContent = i; } // 推荐: cache DOM 引用 const counterElement = document.getElementById('counter'); for (let i = 0; i < 1000; i++) { counterElement.textContent = i; }

8.2 usingdocumentation片段

// 不推荐: 频繁modify DOM const list = document.getElementById('myList'); for (let i = 0; i < 1000; i++) { const li = document.createElement('li'); li.textContent = `Item ${i}`; list.appendChild(li); } // 推荐: usingdocumentation片段 const list = document.getElementById('myList'); const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { const li = document.createElement('li'); li.textContent = `Item ${i}`; fragment.appendChild(li); } list.appendChild(fragment);

8.3 批量update样式

// 不推荐: 频繁modify样式 const element = document.getElementById('myElement'); element.style.color = 'red'; element.style.fontSize = '18px'; element.style.backgroundColor = '#f0f0f0'; // 推荐: using CSS class element.className = 'highlight'; // or using classList element.classList.add('highlight');

实践case: 动态creation导航菜单

fake设我们需要根据data动态creation一个导航菜单:

// 导航菜单data const menuItems = [ { text: '首页', url: '#' }, { text: '产品', url: '#' }, { text: 'service', url: '#' }, { text: 'About Us', url: '#' }, { text: 'Contact Us', url: '#' } ]; // 获取containers const navContainer = document.getElementById('nav-container'); // creation导航元素 const nav = document.createElement('nav'); const ul = document.createElement('ul'); ul.style.listStyle = 'none'; ul.style.display = 'flex'; ul.style.gap = '20px'; ul.style.padding = '0'; ul.style.margin = '0'; // 遍历datacreation菜单项 menuItems.forEach(item => { const li = document.createElement('li'); const a = document.createElement('a'); a.href = item.url; a.textContent = item.text; a.style.textDecoration = 'none'; a.style.color = '#4285F4'; a.style.fontWeight = '500'; a.addEventListener('mouseover', function() { this.style.textDecoration = 'underline'; }); a.addEventListener('mouseout', function() { this.style.textDecoration = 'none'; }); li.appendChild(a); ul.appendChild(li); }); // 组装导航 nav.appendChild(ul); navContainer.appendChild(nav); console.log('导航菜单creationcompletion!');

互动练习: DOM operation实践

请completion以 under DOM operationtask:

  1. creation一个package含 5 个project 待办事项list
  2. for 每个project添加delete按钮
  3. implementation添加 new 待办事项 functions
  4. implementationdelete待办事项 functions

待办事项list