掌握 JavaScript 中的 DOM 操作:综合指南

JavaScript 中的 DOM 操作

**DOM 操作** 是现代 Web 开发的一个基本方面,它允许开发人员动态修改网页的内容、结构和样式。文档对象模型 (DOM) 以树状格式表示网页的 HTML 结构。

1.什么是 DOM?

DOM 是浏览器提供的一个接口,允许 JavaScript 与 HTML 和 CSS 交互。它将页面表示为一个节点树,其中每个元素、属性或文本都是一个节点。

例子:

对于下面的 HTML:

Hello, World!

DOM 结构如下所示:

  • 文档 HTML 主体 Div (id="container") 段落 ("Hello, World!")
  • 2.选择 DOM 元素

    A.使用 getElementById

    根据 ID 选择一个元素。

    const container = document.getElementById("container");
    console.log(container); // Output: 
    ...

    B.使用 querySelector

    选择第一个匹配的元素。

    const paragraph = document.querySelector("p");
    console.log(paragraph); // Output: 

    Hello, World!

    C.使用 querySelectorAll

    选择所有匹配的元素作为 NodeList。

    const allParagraphs = document.querySelectorAll("p");
    console.log(allParagraphs); // Output: NodeList of 

    elements

    3.修改DOM元素

    A. 更改内容

    使用“textContent”或“innerHTML”属性来修改内容。

    const paragraph = document.querySelector("p");
    paragraph.textContent = "Hello, JavaScript!";
    // Changes 

    Hello, World!

    to

    Hello, JavaScript!

    B. 改变属性

    使用“setAttribute”或直接属性分配。

    const image = document.querySelector("img");
    image.setAttribute("src", "new-image.jpg");
    image.alt = "A descriptive text";

    C. 风格转变

    修改“style”属性以应用内联样式。

    const container = document.getElementById("container");
    container.style.backgroundColor = "lightblue";
    container.style.padding = "20px";

    4. 添加和删除元素

    A. 创建新元素

    使用“createElement”方法。

    const newParagraph = document.createElement("p");
    newParagraph.textContent = "This is a new paragraph.";
    document.body.appendChild(newParagraph);

    B. 删除元素

    使用“remove”方法或“removeChild”。

    const paragraph = document.querySelector("p");
    paragraph.remove(); // Removes the paragraph from the DOM

    5. 为元素添加事件监听器

    您可以使用事件监听器为元素添加交互性。

    const button = document.createElement("button");
    button.textContent = "Click Me";
    
    button.addEventListener("click", function() {
      alert("Button clicked!");
    });
    
    document.body.appendChild(button);

    6. 遍历 DOM

    在父元素、子元素和兄弟元素之间导航。

    A. 父母与孩子

    const child = document.querySelector("p");
    const parent = child.parentElement;
    console.log(parent); // Output: Parent element of 

    const children = parent.children; console.log(children); // Output: HTMLCollection of child elements

    B. 兄弟姐妹

    const sibling = child.nextElementSibling;
    console.log(sibling); // Output: Next sibling element

    7.性能优化

  • 使用 documentFragment 进行批量更新:通过分组 DOM 更新来最大限度地减少重排和重绘。
  • const fragment = document.createDocumentFragment();
       for (let i = 0; i < 5; i++) {
         const li = document.createElement("li");
         li.textContent = `Item ${i + 1}`;
         fragment.appendChild(li);
       }
       document.querySelector("ul").appendChild(fragment);
  • 最小化直接 DOM 操作:缓存元素并批量修改它们。
  • 使用虚拟 DOM 库:对于复杂的应用程序,请考虑使用 React 或 Vue 等库。
  • 8.实例:待办事项清单

    const input = document.createElement("input");
    const button = document.createElement("button");
    button.textContent = "Add Task";
    
    button.addEventListener("click", function() {
      const task = document.createElement("li");
      task.textContent = input.value;
      document.querySelector("ul").appendChild(task);
      input.value = ""; // Clear the input field
    });
    
    document.body.appendChild(input);
    document.body.appendChild(button);
    document.body.appendChild(document.createElement("ul"));

    9. 总结

  • DOM 操作允许开发人员动态修改网页。
  • 使用 getElementById、querySelector 和 createElement 等方法进行有效操作。
  • 尽量减少直接 DOM 操作以获得更好的性能。
  • 掌握 DOM 操作对于创建动态、交互且用户友好的 Web 应用程序至关重要。

    **嗨,我是 Abhay Singh Kathayat!**

    我是一名全栈开发人员,精通前端和后端技术。我使用多种编程语言和框架来构建高效、可扩展且用户友好的应用程序。

    请随时通过我的商务电子邮件联系我:kaashshorts28@gmail.com。